Overview

Namespaces

  • Glpi
    • Cache
    • Console
      • Command
      • Database
      • Ldap
      • Migration
      • Task
    • Exception
  • None

Classes

  • AbstractQuery
  • Ajax
  • Alert
  • API
  • APIClient
  • APIRest
  • APIXmlrpc
  • Auth
  • AuthLDAP
  • AuthLdapReplicate
  • AuthMail
  • AutoUpdateSystem
  • Backup
  • Blacklist
  • BlacklistedMailContent
  • Budget
  • BudgetType
  • BusinessCriticity
  • Calendar
  • Calendar_Holiday
  • CalendarSegment
  • Cartridge
  • CartridgeItem
  • CartridgeItem_PrinterModel
  • CartridgeItemType
  • Central
  • Certificate
  • Certificate_Item
  • CertificateType
  • Change
  • Change_Group
  • Change_Item
  • Change_Problem
  • Change_Supplier
  • Change_Ticket
  • Change_User
  • ChangeCost
  • ChangeTask
  • ChangeValidation
  • CliMigration
  • CommonDBChild
  • CommonDBConnexity
  • CommonDBRelation
  • CommonDBTM
  • CommonDBVisible
  • CommonDCModelDropdown
  • CommonDevice
  • CommonDeviceModel
  • CommonDeviceType
  • CommonDropdown
  • CommonGLPI
  • CommonImplicitTreeDropdown
  • CommonITILActor
  • CommonITILCost
  • CommonITILObject
  • CommonITILTask
  • CommonITILValidation
  • CommonTreeDropdown
  • Computer
  • Computer_Item
  • Computer_SoftwareLicense
  • Computer_SoftwareVersion
  • ComputerAntivirus
  • ComputerModel
  • ComputerType
  • ComputerVirtualMachine
  • Config
  • Consumable
  • ConsumableItem
  • ConsumableItemType
  • Contact
  • Contact_Supplier
  • ContactType
  • Contract
  • Contract_Item
  • Contract_Supplier
  • ContractCost
  • ContractType
  • CronTask
  • CronTaskLog
  • Datacenter
  • DBConnection
  • DBmysql
  • DBmysqlIterator
  • DbUtils
  • DCRoom
  • DeviceBattery
  • DeviceBatteryModel
  • DeviceBatteryType
  • DeviceCase
  • DeviceCaseModel
  • DeviceCaseType
  • DeviceControl
  • DeviceControlModel
  • DeviceDrive
  • DeviceDriveModel
  • DeviceFirmware
  • DeviceFirmwareModel
  • DeviceFirmwareType
  • DeviceGeneric
  • DeviceGenericModel
  • DeviceGenericType
  • DeviceGraphicCard
  • DeviceGraphicCardModel
  • DeviceHardDrive
  • DeviceHardDriveModel
  • DeviceMemory
  • DeviceMemoryModel
  • DeviceMemoryType
  • DeviceMotherboard
  • DeviceMotherBoardModel
  • DeviceNetworkCard
  • DeviceNetworkCardModel
  • DevicePci
  • DevicePciModel
  • DevicePowerSupply
  • DevicePowerSupplyModel
  • DeviceProcessor
  • DeviceProcessorModel
  • DeviceSensor
  • DeviceSensorModel
  • DeviceSensorType
  • DeviceSimcard
  • DeviceSimcardType
  • DeviceSoundCard
  • DeviceSoundCardModel
  • DisplayPreference
  • Document
  • Document_Item
  • DocumentCategory
  • DocumentType
  • Domain
  • Dropdown
  • DropdownTranslation
  • Enclosure
  • EnclosureModel
  • Entity
  • Entity_KnowbaseItem
  • Entity_Reminder
  • Entity_RSSFeed
  • Fieldblacklist
  • FieldUnicity
  • Filesystem
  • FQDN
  • FQDNLabel
  • GLPI
  • Glpi\Cache\SimpleCache
  • Glpi\Console\AbstractCommand
  • Glpi\Console\Application
  • Glpi\Console\CommandLoader
  • Glpi\Console\Database\CheckCommand
  • Glpi\Console\Database\InstallCommand
  • Glpi\Console\Database\UpdateCommand
  • Glpi\Console\Ldap\SynchronizeUsersCommand
  • Glpi\Console\Migration\BuildMissingTimestampsCommand
  • Glpi\Console\Migration\MyIsamToInnoDbCommand
  • Glpi\Console\Task\UnlockCommand
  • Glpi\Event
  • GLPIMailer
  • GLPINetwork
  • GLPIPDF
  • GLPIUploadHandler
  • Group
  • Group_KnowbaseItem
  • Group_Problem
  • Group_Reminder
  • Group_RSSFeed
  • Group_Ticket
  • Group_User
  • Holiday
  • Html
  • HTMLTableBase
  • HTMLTableCell
  • HTMLTableEntity
  • HTMLTableGroup
  • HTMLTableHeader
  • HTMLTableMain
  • HTMLTableRow
  • HTMLTableSubHeader
  • HTMLTableSuperHeader
  • Infocom
  • InterfaceType
  • IPAddress
  • IPAddress_IPNetwork
  • IPNetmask
  • IPNetwork
  • IPNetwork_Vlan
  • Item_DeviceBattery
  • Item_DeviceCase
  • Item_DeviceControl
  • Item_DeviceDrive
  • Item_DeviceFirmware
  • Item_DeviceGeneric
  • Item_DeviceGraphicCard
  • Item_DeviceHardDrive
  • Item_DeviceMemory
  • Item_DeviceMotherboard
  • Item_DeviceNetworkCard
  • Item_DevicePci
  • Item_DevicePowerSupply
  • Item_DeviceProcessor
  • Item_Devices
  • Item_DeviceSensor
  • Item_DeviceSimcard
  • Item_DeviceSoundCard
  • Item_Disk
  • Item_Enclosure
  • Item_OperatingSystem
  • Item_Problem
  • Item_Project
  • Item_Rack
  • Item_Ticket
  • Itil_Project
  • ITILCategory
  • ITILFollowup
  • ITILSolution
  • Knowbase
  • KnowbaseItem
  • KnowbaseItem_Comment
  • KnowbaseItem_Item
  • KnowbaseItem_Profile
  • KnowbaseItem_Revision
  • KnowbaseItem_User
  • KnowbaseItemCategory
  • KnowbaseItemTranslation
  • LevelAgreement
  • LevelAgreementLevel
  • Line
  • LineOperator
  • LineType
  • Link
  • Link_Itemtype
  • Location
  • Lock
  • Log
  • MailCollector
  • Manufacturer
  • MassiveAction
  • Migration
  • MigrationCleaner
  • Monitor
  • MonitorModel
  • MonitorType
  • Netpoint
  • Network
  • NetworkAlias
  • NetworkEquipment
  • NetworkEquipmentModel
  • NetworkEquipmentType
  • NetworkInterface
  • NetworkName
  • NetworkPort
  • NetworkPort_NetworkPort
  • NetworkPort_Vlan
  • NetworkPortAggregate
  • NetworkPortAlias
  • NetworkPortDialup
  • NetworkPortEthernet
  • NetworkPortFiberchannel
  • NetworkPortInstantiation
  • NetworkPortLocal
  • NetworkPortMigration
  • NetworkPortWifi
  • Notepad
  • Notification
  • Notification_NotificationTemplate
  • NotificationAjax
  • NotificationAjaxSetting
  • NotificationEvent
  • NotificationEventAbstract
  • NotificationEventAjax
  • NotificationEventMailing
  • NotificationMailing
  • NotificationMailingSetting
  • NotificationSetting
  • NotificationSettingConfig
  • NotificationTarget
  • NotificationTargetCartridgeItem
  • NotificationTargetCertificate
  • NotificationTargetChange
  • NotificationTargetCommonITILObject
  • NotificationTargetConsumableItem
  • NotificationTargetContract
  • NotificationTargetCrontask
  • NotificationTargetDBConnection
  • NotificationTargetFieldUnicity
  • NotificationTargetInfocom
  • NotificationTargetMailCollector
  • NotificationTargetObjectLock
  • NotificationTargetPlanningRecall
  • NotificationTargetProblem
  • NotificationTargetProject
  • NotificationTargetProjectTask
  • NotificationTargetReservation
  • NotificationTargetSavedsearch_Alert
  • NotificationTargetSoftwareLicense
  • NotificationTargetTicket
  • NotificationTargetUser
  • NotificationTemplate
  • NotificationTemplateTranslation
  • NotImportedEmail
  • ObjectLock
  • OLA
  • OlaLevel
  • OlaLevel_Ticket
  • OlaLevelAction
  • OlaLevelCriteria
  • OperatingSystem
  • OperatingSystemArchitecture
  • OperatingSystemEdition
  • OperatingSystemKernel
  • OperatingSystemKernelVersion
  • OperatingSystemServicePack
  • OperatingSystemVersion
  • PDU
  • Pdu_Plug
  • PDU_Rack
  • PDUModel
  • PDUType
  • Peripheral
  • PeripheralModel
  • PeripheralType
  • Phone
  • PhoneModel
  • PhonePowerSupply
  • PhoneType
  • Planning
  • PlanningRecall
  • Plug
  • Plugin
  • Preference
  • Printer
  • PrinterModel
  • PrinterType
  • Problem
  • Problem_Supplier
  • Problem_Ticket
  • Problem_User
  • ProblemCost
  • ProblemTask
  • Profile
  • Profile_Reminder
  • Profile_RSSFeed
  • Profile_User
  • ProfileRight
  • Project
  • ProjectCost
  • ProjectState
  • ProjectTask
  • ProjectTask_Ticket
  • ProjectTaskTeam
  • ProjectTaskTemplate
  • ProjectTaskType
  • ProjectTeam
  • ProjectType
  • PurgeLogs
  • QueryExpression
  • QueryParam
  • QuerySubQuery
  • QueryUnion
  • QueuedNotification
  • Rack
  • RackModel
  • RackType
  • RegisteredID
  • Reminder
  • Reminder_User
  • Report
  • RequestType
  • Reservation
  • ReservationItem
  • RSSFeed
  • RSSFeed_User
  • Rule
  • RuleAction
  • RuleAsset
  • RuleAssetCollection
  • RuleCollection
  • RuleCriteria
  • RuleDictionnaryComputerModel
  • RuleDictionnaryComputerModelCollection
  • RuleDictionnaryComputerType
  • RuleDictionnaryComputerTypeCollection
  • RuleDictionnaryDropdown
  • RuleDictionnaryDropdownCollection
  • RuleDictionnaryManufacturer
  • RuleDictionnaryManufacturerCollection
  • RuleDictionnaryMonitorModel
  • RuleDictionnaryMonitorModelCollection
  • RuleDictionnaryMonitorType
  • RuleDictionnaryMonitorTypeCollection
  • RuleDictionnaryNetworkEquipmentModel
  • RuleDictionnaryNetworkEquipmentModelCollection
  • RuleDictionnaryNetworkEquipmentType
  • RuleDictionnaryNetworkEquipmentTypeCollection
  • RuleDictionnaryOperatingSystem
  • RuleDictionnaryOperatingSystemArchitecture
  • RuleDictionnaryOperatingSystemArchitectureCollection
  • RuleDictionnaryOperatingSystemCollection
  • RuleDictionnaryOperatingSystemServicePack
  • RuleDictionnaryOperatingSystemServicePackCollection
  • RuleDictionnaryOperatingSystemVersion
  • RuleDictionnaryOperatingSystemVersionCollection
  • RuleDictionnaryPeripheralModel
  • RuleDictionnaryPeripheralModelCollection
  • RuleDictionnaryPeripheralType
  • RuleDictionnaryPeripheralTypeCollection
  • RuleDictionnaryPhoneModel
  • RuleDictionnaryPhoneModelCollection
  • RuleDictionnaryPhoneType
  • RuleDictionnaryPhoneTypeCollection
  • RuleDictionnaryPrinter
  • RuleDictionnaryPrinterCollection
  • RuleDictionnaryPrinterModel
  • RuleDictionnaryPrinterModelCollection
  • RuleDictionnaryPrinterType
  • RuleDictionnaryPrinterTypeCollection
  • RuleDictionnarySoftware
  • RuleDictionnarySoftwareCollection
  • RuleImportComputer
  • RuleImportComputerCollection
  • RuleImportEntity
  • RuleImportEntityCollection
  • RuleMailCollector
  • RuleMailCollectorCollection
  • RuleRight
  • RuleRightCollection
  • RuleRightParameter
  • RuleSoftwareCategory
  • RuleSoftwareCategoryCollection
  • RuleTicket
  • RuleTicketCollection
  • SavedSearch
  • SavedSearch_Alert
  • SavedSearch_User
  • Search
  • Session
  • SingletonRuleList
  • SLA
  • SlaLevel
  • SlaLevel_Ticket
  • SlaLevelAction
  • SlaLevelCriteria
  • SLM
  • Software
  • SoftwareCategory
  • SoftwareLicense
  • SoftwareLicenseType
  • SoftwareVersion
  • SolutionTemplate
  • SolutionType
  • SsoVariable
  • Stat
  • State
  • Supplier
  • Supplier_Ticket
  • SupplierType
  • TaskCategory
  • TaskTemplate
  • Telemetry
  • Ticket
  • Ticket_Ticket
  • Ticket_User
  • TicketCost
  • TicketFollowup
  • TicketRecurrent
  • TicketSatisfaction
  • TicketTask
  • TicketTemplate
  • TicketTemplateHiddenField
  • TicketTemplateMandatoryField
  • TicketTemplatePredefinedField
  • TicketValidation
  • Timer
  • Toolbox
  • Transfer
  • Update
  • User
  • UserCategory
  • UserEmail
  • UserTitle
  • VirtualMachineState
  • VirtualMachineSystem
  • VirtualMachineType
  • Vlan
  • WifiNetwork
  • XHProf
  • XML

Interfaces

  • Glpi\Console\Command\ForceNoPluginsOptionCommandInterface
  • NotificationEventInterface
  • NotificationInterface

Traits

  • DCBreadcrumb

Exceptions

  • CommonDBConnexityItemNotFound
  • Glpi\Exception\ForgetPasswordException
  • Glpi\Exception\PasswordTooWeakException
  • HTMLTableCellFatherCoherentHeader
  • HTMLTableCellFatherSameRow
  • HTMLTableCellWithoutFather
  • HTMLTableUnknownHeader
  • HTMLTableUnknownHeaders
  • HTMLTableUnknownHeadersOrder

Functions

  • __
  • __s
  • _n
  • _nx
  • _sn
  • _sx
  • _x
  • autoName
  • closeDBConnections
  • contructListFromTree
  • contructTreeFromList
  • countDistinctElementsInTable
  • countElementsInTable
  • countElementsInTableForEntity
  • countElementsInTableForMyEntities
  • exportArrayToDB
  • formatUserName
  • get_hour_from_sql
  • getAllDatasFromTable
  • getAncestorsOf
  • getDateCriteria
  • getDateRequest
  • getDbRelations
  • getEntitiesRestrictCriteria
  • getEntitiesRestrictRequest
  • getForeignKeyFieldForItemType
  • getForeignKeyFieldForTable
  • getItemForItemtype
  • getItemtypeForForeignKeyField
  • getItemTypeForTable
  • getNextItem
  • getPlural
  • getPreviousItem
  • getRealQueryForTreeItem
  • getSingular
  • getSonsAndAncestorsOf
  • getSonsOf
  • getTableForItemType
  • getTableNameForForeignKeyField
  • getTreeForItem
  • getTreeLeafValueName
  • getTreeValueCompleteName
  • getTreeValueName
  • getUserName
  • glpi_autoload
  • importArrayFromDB
  • isAPI
  • isCommandLine
  • isForeignKeyField
  • isIndex
  • isPluginItemType
  • regenerateTreeCompleteName
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Todo
   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: 
<?php
/**
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2015-2018 Teclib' and contributors.
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * GLPI 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 2 of the License, or
 * (at your option) any later version.
 *
 * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 */

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

/**
 * LevelAgreement base Class for OLA & SLA
 * @since 9.2
**/

abstract class LevelAgreement extends CommonDBChild {
   // From CommonDBTM
   var $dohistory          = true;
   static $rightname       = 'slm';

   // From CommonDBChild
   static public $itemtype = 'SLM';
   static public $items_id = 'slms_id';


   /**
    * Display a specific OLA or SLA warning.
    * Called into the above showForm() function
    *
    * @return void
    */
   abstract function showFormWarning();

   /**
    * Return the text needed for a confirmation of adding level agreement to a ticket
    *
    * @return array of strings
    */
   abstract function getAddConfirmation();

   /**
    * Get table fields
    *
    * @param integer $subtype of OLA/SLA, can be SLM::TTO or SLM::TTR
    *
    * @return array of 'date' and 'sla' field names
    */
   static function getFieldNames($subtype) {

      $dateField = null;
      $laField  = null;

      switch ($subtype) {
         case SLM::TTO:
            $dateField = static::$prefixticket.'time_to_own';
            $laField   = static::$prefix.'s_id_tto';
            break;

         case SLM::TTR:
            $dateField = static::$prefixticket.'time_to_resolve';
            $laField   = static::$prefix.'s_id_ttr';
            break;
      }
      return [$dateField, $laField];
   }

   function defineTabs($options = []) {

      $ong = [];
      $this->addDefaultFormTab($ong);
      $this->addStandardTab(static::$levelclass, $ong, $options);
      $this->addStandardTab('Rule', $ong, $options);
      $this->addStandardTab('Ticket', $ong, $options);

      return $ong;
   }

   /**
    * Define calendar of the ticket using the SLA/OLA when using this calendar as sla/ola-s calendar
    *
    * @param integer $calendars_id calendars_id of the ticket
   **/
   function setTicketCalendar($calendars_id) {

      if ($this->fields['calendars_id'] == -1) {
         $this->fields['calendars_id'] = $calendars_id;
      }
   }

   function post_getFromDB() {
      // get calendar from slm
      $slm = new SLM;
      if ($slm->getFromDB($this->fields['slms_id'])) {
         $this->fields['calendars_id'] = $slm->fields['calendars_id'];
      }
   }

   function post_getEmpty() {
      $this->fields['number_time'] = 4;
      $this->fields['definition_time'] = 'hour';
   }

   /**
    * Print the form
    *
    * @param $ID        integer  ID of the item
    * @param $options   array    of possible options:
    *     - target filename : where to go when done.
    *     - withtemplate boolean : template or basic item
    *
    *@return boolean item found
   **/
   function showForm($ID, $options = []) {
      $rowspan = 3;
      if ($ID > 0) {
         $rowspan = 5;
      }

      // Get SLM object
      $slm = new SLM();
      if (isset($options['parent'])) {
         $slm = $options['parent'];
      } else {
         $slm->getFromDB($this->fields['slms_id']);
      }

      if ($ID > 0) {
         $this->check($ID, READ);
      } else {
         // Create item
         $options[static::$items_id] = $slm->getField('id');

         //force itemtype of parent
         static::$itemtype = get_class($slm);

         $this->check(-1, CREATE, $options);
      }

      $this->showFormHeader($options);
      echo "<tr class='tab_bg_1'>";
      echo "<td>".__('Name')."</td>";
      echo "<td>";
      Html::autocompletionTextField($this, "name", ['value' => $this->fields["name"]]);
      echo "<td rowspan='".$rowspan."'>".__('Comments')."</td>";
      echo "<td rowspan='".$rowspan."'>
            <textarea cols='45' rows='8' name='comment' >".$this->fields["comment"]."</textarea>";
      echo "</td></tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td>".__('SLM')."</td>";
      echo "<td>";
      echo $slm->getLink();
      echo "<input type='hidden' name='slms_id' value='".$this->fields['slms_id']."'>";
      echo "</td></tr>";

      if ($ID > 0) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>".__('Last update')."</td>";
         echo "<td>".($this->fields["date_mod"] ? Html::convDateTime($this->fields["date_mod"])
                                                : __('Never'));
         echo "</td></tr>";
      }

      echo "<tr class='tab_bg_1'><td>".__('Type')."</td>";
      echo "<td>";
      self::getTypeDropdown(['value' => $this->fields["type"]]);
      echo "</td>";
      echo "</tr>";

      echo "<tr class='tab_bg_1'><td>".__('Maximum time')."</td>";
      echo "<td>";
      Dropdown::showNumber("number_time", ['value' => $this->fields["number_time"],
                                           'min'   => 0]);
      $possible_values = ['minute' => _n('Minute', 'Minutes', Session::getPluralNumber()),
                          'hour'   => _n('Hour', 'Hours', Session::getPluralNumber()),
                          'day'    => _n('Day', 'Days', Session::getPluralNumber())];
      $rand = Dropdown::showFromArray('definition_time', $possible_values,
                                      ['value'     => $this->fields["definition_time"],
                                       'on_change' => 'appearhideendofworking()']);
      echo "\n<script type='text/javascript' >\n";
      echo "function appearhideendofworking() {\n";
      echo "if ($('#dropdown_definition_time$rand option:selected').val() == 'day') {
               $('#title_endworkingday').show();
               $('#dropdown_endworkingday').show();
            } else {
               $('#title_endworkingday').hide();
               $('#dropdown_endworkingday').hide();
            }";
      echo "}\n";
      echo "appearhideendofworking();\n";
      echo "</script>\n";

      echo "</td></tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td><div id='title_endworkingday'>".__('End of working day')."</div></td>";
      echo "<td><div id='dropdown_endworkingday'>";
      Dropdown::showYesNo("end_of_working_day", $this->fields["end_of_working_day"]);
      echo "</div></td>";

      echo "<td colspan='2'>";
      $this->showFormWarning();
      echo "</td>";
      echo "</tr>";

      $this->showFormButtons($options);

      return true;
   }


   /**
    * Show for ticket
    *
    * @param  Ticket         $ticket Ticket item
    * @param  integer        $type
    * @param  TicketTemplate $tt ticket template object
    * @param  bool           $canupdate update right
    */
   function showForTicket(Ticket $ticket, $type, $tt, $canupdate) {
      list($dateField, $laField) = static::getFieldNames($type);
      $rand = mt_rand();
      $pre  = static::$prefix;
      echo "<table width='100%'>";
      echo "<tr class='tab_bg_1'>";

      if (!isset($ticket->fields[$dateField]) || $ticket->fields[$dateField] == 'NULL') {
         $ticket->fields[$dateField]='';
      }

      if ($ticket->fields['id']) {
         if ($this->getDataForTicket($ticket->fields['id'], $type)) {
            echo "<td style='width: 105px'>";
            echo $tt->getBeginHiddenFieldValue($dateField);
            echo Html::convDateTime($ticket->fields[$dateField]);
            echo $tt->getEndHiddenFieldValue($dateField, $ticket);
            echo "</td>";
            echo "<td>";
            echo $tt->getBeginHiddenFieldText($laField);
            echo "<i class='far fa-clock slt'></i>";
            echo Dropdown::getDropdownName(static::getTable(),
                                           $ticket->fields[$laField])."&nbsp;";
            echo Html::hidden($laField, ['value' => $ticket->fields[$laField]]);
            $comment = isset($this->fields['comment']) ? $this->fields['comment'] : '';
            $level      = new static::$levelclass();
            $nextaction = new static::$levelticketclass();
            if ($nextaction->getFromDBForTicket($ticket->fields["id"], $type)) {
               $comment .= '<br/><span class="b spaced">'.
                             sprintf(__('Next escalation: %s'),
                                     Html::convDateTime($nextaction->fields['date'])).
                           '</span><br>';
               if ($level->getFromDB($nextaction->fields[$pre.'levels_id'])) {
                  $comment .= '<span class="b spaced">'.
                                sprintf(__('%1$s: %2$s'), __('Escalation level'),
                                        $level->getName()).
                              '</span>';
               }
            }

            $options = [];
            if (Session::haveRight('slm', READ)) {
               $options['link'] = $this->getLinkURL();
            }
            Html::showToolTip($comment, $options);
            if ($canupdate) {
               $delete_field = strtolower(get_called_class())."_delete";
               $fields = [$delete_field       => $delete_field,
                          'id'                => $ticket->getID(),
                          'type'              => $type,
                          '_glpi_csrf_token'  => Session::getNewCSRFToken(),
                          '_glpi_simple_form' => 1];
               $ticket_url = $ticket->getFormURL();
               echo Html::scriptBlock("
               function delete_date$type$rand(e) {
                  e.preventDefault();

                  if (nativeConfirm('".addslashes(__('Also delete date?'))."')) {
                     submitGetLink('$ticket_url',
                                   ".json_encode(array_merge($fields, ['delete_date' => 1])).");
                  } else {
                     submitGetLink('$ticket_url',
                                   ".json_encode(array_merge($fields, ['delete_date' => 0])).");
                  }
               }");
               echo "<a class='fa fa-times-circle pointer'
                        onclick='delete_date$type$rand(event)'
                        title='"._sx('button', 'Delete permanently')."'>";
               echo "<span class='sr-only'>"._x('button', 'Delete permanently')."</span>";
               echo "</a>";
            }
            echo $tt->getEndHiddenFieldText($laField);
            echo "</td>";

         } else {
            echo "<td width='200px'>";
            echo $tt->getBeginHiddenFieldValue($dateField);
            echo "<span class='assign_la'>";
            if ($canupdate) {
               Html::showDateTimeField($dateField, ['value'      => $ticket->fields[$dateField],
                                                    'timestep'   => 1,
                                                    'maybeempty' => true]);
            } else {
               echo Html::convDateTime($ticket->fields[$dateField]);
            }
            echo "</span>";
            echo $tt->getEndHiddenFieldValue($dateField, $ticket);
            $data     = $this->find(
               ['type' => $type] + getEntitiesRestrictCriteria('', '', $ticket->fields['entities_id'], true)
            );
            if ($canupdate
                && !empty($data)) {
               echo $tt->getBeginHiddenFieldText($laField);
               echo "<span id='la_action$type$rand' class='assign_la'>";
               echo "<a ".Html::addConfirmationOnAction($this->getAddConfirmation(),
                        "cleanhide('la_action$type$rand');cleandisplay('la_choice$type$rand');").
                    " class='pointer' title='".static::getTypeName()."'>
                    <i class='far fa-clock slt'></i></a>";
               echo "</span>";
               echo "<span id='la_choice$type$rand' style='display:none' class='assign_la'>";
               echo "<i class='far fa-clock slt'></i>";
               echo "<span class='b'>".static::getTypeName()."</span>&nbsp;";
               static::dropdown([
                  'name'      => $laField,
                  'entity'    => $ticket->fields["entities_id"],
                  'condition' => ['type' => $type]
               ]);
               echo "</span>";
               echo $tt->getEndHiddenFieldText($laField);
            }
            echo "</td>";
         }

      } else { // New Ticket
         echo "<td>";
         echo $tt->getBeginHiddenFieldValue($dateField);
         Html::showDateTimeField($dateField, ['value'      => $ticket->fields[$dateField],
                                              'timestep'   => 1,
                                              'maybeempty' => false,
                                              'canedit'    => $canupdate,
                                              'required'   => $tt->isMandatoryField($dateField)]);
         echo $tt->getEndHiddenFieldValue($dateField, $ticket);
         echo "</td>";
         $data     = $this->find(
            ['type' => $type] + getEntitiesRestrictCriteria('', '', $ticket->fields['entities_id'], true)
         );
         if ($canupdate
             && !empty($data)) {
            echo $tt->getBeginHiddenFieldText($laField);
            if (!$tt->isHiddenField($laField) || $tt->isPredefinedField($laField)) {
               echo "<th>".sprintf(__('%1$s%2$s'),
                                   static::getTypeName(),
                                   $tt->getMandatoryMark($laField))."</th>";
            }
            echo $tt->getEndHiddenFieldText($laField);
            echo "<td class='nopadding'>".$tt->getBeginHiddenFieldValue($laField);
            static::dropdown([
               'name'      => $laField,
               'entity'    => $ticket->fields["entities_id"],
               'value'     => isset($ticket->fields[$laField]) ? $ticket->fields[$laField] : 0,
               'condition' => ['type' => $type]
            ]);
            echo $tt->getEndHiddenFieldValue($laField, $ticket);
            echo "</td>";
         }
      }

      echo "</tr>";
      echo "</table>";
   }


   /**
    * Print the HTML for a SLM
    *
    * @param SLM $slm Slm item
    */
   static function showForSLM(SLM $slm) {
      global $CFG_GLPI;

      if (!$slm->can($slm->fields['id'], READ)) {
         return false;
      }

      $instID   = $slm->fields['id'];
      $la       = new static();
      $calendar = new Calendar();
      $rand     = mt_rand();
      $canedit  = ($slm->canEdit($instID)
                   && Session::getCurrentInterface() == "central");

      if ($canedit) {
         echo "<div id='showLa$instID$rand'></div>\n";

         echo "<script type='text/javascript' >";
         echo "function viewAddLa$instID$rand() {";
         $params = ['type'                     => $la->getType(),
                    'parenttype'               => $slm->getType(),
                    $slm->getForeignKeyField() => $instID,
                    'id'                       => -1];
         Ajax::updateItemJsCode("showLa$instID$rand",
                                $CFG_GLPI["root_doc"]."/ajax/viewsubitem.php", $params);
         echo "}";
         echo "</script>";
         echo "<div class='center firstbloc'>".
               "<a class='vsubmit' href='javascript:viewAddLa$instID$rand();'>";
         echo __('Add a new item')."</a></div>\n";
      }

      // list
      $laList = $la->find(['slms_id' => $instID]);
      Session::initNavigateListItems(__CLASS__,
                                     sprintf(__('%1$s = %2$s'),
                                             $slm::getTypeName(1),
                                             $slm->getName()));
      echo "<div class='spaced'>";
      if (count($laList)) {
         if ($canedit) {
            Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
            $massiveactionparams = ['container' => 'mass'.__CLASS__.$rand];
            Html::showMassiveActions($massiveactionparams);
         }

         echo "<table class='tab_cadre_fixehov'>";
         $header_begin  = "<tr>";
         $header_top    = '';
         $header_bottom = '';
         $header_end    = '';
         if ($canedit) {
            $header_top .= "<th width='10'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
            $header_top .= "</th>";
            $header_bottom .= "<th width='10'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand);
            $header_bottom .= "</th>";
         }
         $header_end .= "<th>".__('Name')."</th>";
         $header_end .= "<th>".__('Type')."</th>";
         $header_end .= "<th>".__('Maximum time')."</th>";
         $header_end .= "<th>".__('Calendar')."</th>";

         echo $header_begin.$header_top.$header_end;
         foreach ($laList as $val) {
            $edit = ($canedit ? "style='cursor:pointer' onClick=\"viewEditLa".
                        $instID.$val["id"]."$rand();\""
                        : '');
            echo "<script type='text/javascript' >";
            echo "function viewEditLa".$instID.$val["id"]."$rand() {";
            $params = ['type'                     => $la->getType(),
                       'parenttype'               => $slm->getType(),
                       $slm->getForeignKeyField() => $instID,
                       'id'                       => $val["id"]];
            Ajax::updateItemJsCode("showLa$instID$rand",
                                   $CFG_GLPI["root_doc"]."/ajax/viewsubitem.php", $params);
            echo "};";
            echo "</script>\n";

            echo "<tr class='tab_bg_1'>";
            echo "<td width='10' $edit>";
            if ($canedit) {
               Html::showMassiveActionCheckBox($la->getType(), $val['id']);
            }
            echo "</td>";
            $la->getFromDB($val['id']);
            echo "<td $edit>".$la->getLink()."</td>";
            echo "<td $edit>".$la->getSpecificValueToDisplay('type', $la->fields['type'])."</td>";
            echo "<td $edit>";
            echo $la->getSpecificValueToDisplay('number_time',
                  ['number_time'     => $la->fields['number_time'],
                   'definition_time' => $la->fields['definition_time']]);
            echo "</td>";
            if (!$slm->fields['calendars_id']) {
               $link =  __('24/7');
            } else if ($slm->fields['calendars_id'] == -1) {
               $link = __('Calendar of the ticket');
            } else if ($calendar->getFromDB($slm->fields['calendars_id'])) {
               $link = $calendar->getLink();
            }
            echo "<td $edit>".$link."</td>";
            echo "</tr>";
         }
         echo $header_begin.$header_bottom.$header_end;
         echo "</table>";

         if ($canedit) {
            $massiveactionparams['ontop'] = false;
            Html::showMassiveActions($massiveactionparams);
            Html::closeForm();
         }
      } else {
         echo __('No item to display');
      }
      echo "</div>";
   }

   /**
    * Display a list of rule for the current sla/ola
    * @return void
    */
   function showRulesList() {
      global $DB;

      $fk      = static::getFieldNames($this->fields['type'])[1];
      $rule    = new RuleTicket;
      $rand    = mt_rand();
      $canedit = self::canUpdate();

      $rules_id_list = iterator_to_array($DB->request([
         'SELECT DISTINCT' => 'rules_id',
         'FROM'            => 'glpi_ruleactions',
         'WHERE'           => [
            'field' => $fk,
            'value' => $this->getID()]]));
      $nb = count($rules_id_list);

      echo "<div class='spaced'>";
      if (!$nb) {
         echo "<table class='tab_cadre_fixehov'>";
         echo "<tr><th>" . __('No item found') . "</th>";
         echo "</tr>\n";
         echo "</table>\n";

      } else {
         if ($canedit) {
            Html::openMassiveActionsForm('massRuleTicket'.$rand);
            $massiveactionparams
               = ['num_displayed'    => min($_SESSION['glpilist_limit'], $nb),
                  'specific_actions' => ['update' => _x('button', 'Update'),
                                         'purge'  => _x('button', 'Delete permanently')]];
            Html::showMassiveActions($massiveactionparams);
         }
         echo "<table class='tab_cadre_fixehov'>";
         $header_begin  = "<tr>";
         $header_top    = '';
         $header_bottom = '';
         $header_end    = '';
         if ($canedit) {
            $header_begin  .= "<th width='10'>";
            $header_top    .= Html::getCheckAllAsCheckbox('massRuleTicket'.$rand);
            $header_bottom .= Html::getCheckAllAsCheckbox('massRuleTicket'.$rand);
            $header_end    .= "</th>";
         }
         $header_end .= "<th>" . RuleTicket::getTypeName($nb) . "</th>";
         $header_end .= "<th>" . __('Active') . "</th>";
         $header_end .= "<th>" . __('Description') . "</th>";
         $header_end .= "</tr>\n";
         echo $header_begin.$header_top.$header_end;

         Session::initNavigateListItems(get_class($this),
                                        sprintf(__('%1$s = %2$s'),
                                                $rule->getTypeName(1), $rule->getName()));

         foreach ($rules_id_list as $data) {
            $rule->getFromDB($data['rules_id']);
            Session::addToNavigateListItems(get_class($this), $rule->fields["id"]);
            echo "<tr class='tab_bg_1'>";

            if ($canedit) {
               echo "<td width='10'>";
               Html::showMassiveActionCheckBox("RuleTicket", $rule->fields["id"]);
               echo "</td>";
               $ruleclassname = get_class($rule);
               echo "<td><a href='".$ruleclassname::getFormURLWithID($rule->fields["id"])
                       . "&amp;onglet=1'>" .$rule->fields["name"] ."</a></td>";

            } else {
               echo "<td>" . $rule->fields["name"] . "</td>";
            }

            echo "<td>" . Dropdown::getYesNo($rule->fields["is_active"]) . "</td>";
            echo "<td>" . $rule->fields["description"] . "</td>";
            echo "</tr>\n";
         }
         echo $header_begin.$header_bottom.$header_end;
         echo "</table>\n";

         if ($canedit) {
            $massiveactionparams['ontop'] = false;
            Html::showMassiveActions($massiveactionparams);
            Html::closeForm();
         }
      }
      echo "</div>";
   }

   function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {

      if (!$withtemplate) {
         $nb = 0;
         switch ($item->getType()) {
            case 'SLM' :
               if ($_SESSION['glpishow_count_on_tabs']) {
                  $nb = countElementsInTable(self::getTable(),
                                             ['slms_id' => $item->getField('id')]);
               }
               return self::createTabEntry(static::getTypeName($nb), $nb);
         }
      }
      return '';
   }


   static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {

      switch ($item->getType()) {
         case 'SLM' :
            self::showForSLM($item);
            break;
      }
      return true;
   }


   /**
    * Get data by type and ticket
    *
    * @param $tickets_id
    * @param $type
    */
   function getDataForTicket($tickets_id, $type) {
      global $DB;

      list($dateField, $field) = static::getFieldNames($type);

      $iterator = $DB->request([
         'SELECT'       => [static::getTable() . '.id'],
         'FROM'         => static::getTable(),
         'INNER JOIN'   => [
            'glpi_tickets' => [
               'FKEY'   => [
                  static::getTable()   => 'id',
                  'glpi_tickets'       => $field
               ]
            ]
         ],
         'WHERE'        => ['glpi_tickets.id' => $tickets_id],
         'LIMIT'        => 1
      ]);

      if (count($iterator)) {
         return $this->getFromIter($iterator);
      }
      return false;
   }


   function rawSearchOptions() {
      $tab = [];

      $tab[] = [
         'id'                 => 'common',
         'name'               => __('Characteristics')
      ];

      $tab[] = [
         'id'                 => '1',
         'table'              => $this->getTable(),
         'field'              => 'name',
         'name'               => __('Name'),
         'datatype'           => 'itemlink',
         'massiveaction'      => false,
         'autocomplete'       => true,
      ];

      $tab[] = [
         'id'                 => '2',
         'table'              => $this->getTable(),
         'field'              => 'id',
         'name'               => __('ID'),
         'massiveaction'      => false,
         'datatype'           => 'number'
      ];

      $tab[] = [
         'id'                 => '5',
         'table'              => $this->getTable(),
         'field'              => 'number_time',
         'name'               => __('Time'),
         'datatype'           => 'specific',
         'massiveaction'      => false,
         'nosearch'           => true,
         'additionalfields'   => ['definition_time']
      ];

      $tab[] = [
         'id'                 => '6',
         'table'              => $this->getTable(),
         'field'              => 'end_of_working_day',
         'name'               => __('End of working day'),
         'datatype'           => 'bool',
         'massiveaction'      => false
      ];

      $tab[] = [
         'id'                 => '7',
         'table'              => $this->getTable(),
         'field'              => 'type',
         'name'               => __('Type'),
         'datatype'           => 'specific'
      ];

      $tab[] = [
         'id'                 => '8',
         'table'              => 'glpi_slms',
         'field'              => 'name',
         'name'               => __('SLM'),
         'datatype'           => 'dropdown'
      ];

      $tab[] = [
         'id'                 => '16',
         'table'              => $this->getTable(),
         'field'              => 'comment',
         'name'               => __('Comments'),
         'datatype'           => 'text'
      ];

      return $tab;
   }


   /**
    * @param $field
    * @param $values
    * @param $options   array
   **/
   static function getSpecificValueToDisplay($field, $values, array $options = []) {

      if (!is_array($values)) {
         $values = [$field => $values];
      }
      switch ($field) {
         case 'number_time' :
            switch ($values['definition_time']) {
               case 'minute' :
                  return sprintf(_n('%d minute', '%d minutes', $values[$field]), $values[$field]);

               case 'hour' :
                  return sprintf(_n('%d hour', '%d hours', $values[$field]), $values[$field]);

               case 'day' :
                  return sprintf(_n('%d day', '%d days', $values[$field]), $values[$field]);
            }
            break;

         case 'type' :
            return self::getOneTypeName($values[$field]);
      }
      return parent::getSpecificValueToDisplay($field, $values, $options);
   }


   /**
    * @param $field
    * @param $name            (default '')
    * @param $values          (default '')
    * @param $options   array
    *
    * @return string
   **/
   static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {

      if (!is_array($values)) {
         $values = [$field => $values];
      }
      $options['display'] = false;
      switch ($field) {
         case 'type':
            $options['value'] = $values[$field];
            return self::getTypeDropdown($options);
      }
      return parent::getSpecificValueToSelect($field, $name, $values, $options);
   }


   /**
    * Get computed resolution time
    *
    * @return integer resolution time (default 0)
   **/
   function getTime() {

      if (isset($this->fields['id'])) {
         if ($this->fields['definition_time'] == "minute") {
            return $this->fields['number_time'] * MINUTE_TIMESTAMP;
         }
         if ($this->fields['definition_time'] == "hour") {
            return $this->fields['number_time'] * HOUR_TIMESTAMP;
         }
         if ($this->fields['definition_time'] == "day") {
            return $this->fields['number_time'] * DAY_TIMESTAMP;
         }
      }
      return 0;
   }


   /**
    * Get active time between to date time for the active calendar
    *
    * @param datetime $start begin
    * @param datetime $end end
    *
    * @return integer timestamp of delay
    **/
   function getActiveTimeBetween($start, $end) {

      if ($end < $start) {
         return 0;
      }

      if (isset($this->fields['id'])) {
         $cal          = new Calendar();
         $work_in_days = ($this->fields['definition_time'] == 'day');

         // Based on a calendar
         if ($this->fields['calendars_id'] > 0) {
            if ($cal->getFromDB($this->fields['calendars_id'])) {
               return $cal->getActiveTimeBetween($start, $end, $work_in_days);
            }

         } else { // No calendar
            $timestart = strtotime($start);
            $timeend   = strtotime($end);
            return ($timeend-$timestart);
         }
      }
      return 0;
   }


   /**
    * Get date for current agreement
    *
    * @param $start_date         datetime start date
    * @param $additional_delay   integer  additional delay to add or substract (for waiting time)
    *                                     (default 0)
    *
    * @return due date time (NULL if sla/ola not exists)
   **/
   function computeDate($start_date, $additional_delay = 0) {

      if (isset($this->fields['id'])) {
         $delay = $this->getTime();
         // Based on a calendar
         if ($this->fields['calendars_id'] > 0) {
            $cal          = new Calendar();
            $work_in_days = ($this->fields['definition_time'] == 'day');

            if ($cal->getFromDB($this->fields['calendars_id'])) {
               return $cal->computeEndDate($start_date, $delay,
                                           $additional_delay, $work_in_days,
                                           $this->fields['end_of_working_day']);
            }
         }

         // No calendar defined or invalid calendar
         if ($this->fields['number_time'] >= 0) {
            $starttime = strtotime($start_date);
            $endtime   = $starttime + $delay + $additional_delay;
            return date('Y-m-d H:i:s', $endtime);
         }
      }

      return null;
   }


   /**
    * Get execution date of a level
    *
    * @param $start_date         datetime    start date
    * @param $levels_id          integer     sla/ola level id
    * @param $additional_delay   integer     additional delay to add or substract (for waiting time)
    *                                        (default 0)
    *
    * @return execution date time (NULL if ola/sla not exists)
   **/
   function computeExecutionDate($start_date, $levels_id, $additional_delay = 0) {

      if (isset($this->fields['id'])) {
         $level = new static::$levelclass();
         $fk = getForeignKeyFieldForItemType(get_called_class());

         if ($level->getFromDB($levels_id)) { // level exists
            if ($level->fields[$fk] == $this->fields['id']) { // correct level
               $work_in_days = ($this->fields['definition_time'] == 'day');
               $delay        = $this->getTime();

               // Based on a calendar
               if ($this->fields['calendars_id'] > 0) {
                  $cal = new Calendar();
                  if ($cal->getFromDB($this->fields['calendars_id'])) {
                     return $cal->computeEndDate($start_date, $delay,
                                                 $level->fields['execution_time'] + $additional_delay,
                                                 $work_in_days);
                  }
               }
               // No calendar defined or invalid calendar
               $delay    += $additional_delay+$level->fields['execution_time'];
               $starttime = strtotime($start_date);
               $endtime   = $starttime+$delay;
               return date('Y-m-d H:i:s', $endtime);
            }
         }
      }
      return null;
   }


   /**
    * Get types
    *
    * @return array array of types
    **/
   static function getTypes() {
      return [SLM::TTO => __('Time to own'),
              SLM::TTR => __('Time to resolve')];
   }


   /**
    * Get types name
    *
    * @param type $type
    * @return string name
    **/
   static function getOneTypeName($type) {

      $types = self::getTypes();
      $name  = null;
      if (isset($types[$type])) {
         $name = $types[$type];
      }
      return $name;
   }


   /**
    * Get SLA types dropdown
    *
    * @param array $options
    *
    * @return string
    */
   static function getTypeDropdown($options) {

      $params = ['name'  => 'type'];

      foreach ($options as $key => $val) {
         $params[$key] = $val;
      }

      return Dropdown::showFromArray($params['name'], self::getTypes(), $options);
   }


   function prepareInputForAdd($input) {

      if ($input['definition_time'] != 'day') {
         $input['end_of_working_day'] = 0;
      }
      return $input;
   }


   function prepareInputForUpdate($input) {

      if (isset($input['definition_time']) && $input['definition_time'] != 'day') {
         $input['end_of_working_day'] = 0;
      }
      return $input;
   }


   /**
    * Add a level to do for a ticket
    *
    * @param Ticket  $ticket Ticket object
    * @param integer $levels_id SlaLevel or OlaLevel ID
    *
    * @return void
    **/
   function addLevelToDo(Ticket $ticket, $levels_id = 0) {

      $pre = static::$prefix;

      if (!$levels_id && isset($ticket->fields[$pre.'levels_id_ttr'])) {
         $levels_id = $ticket->fields[$pre."levels_id_ttr"];
      }

      if ($levels_id) {
         $toadd = [];
         $date = $this->computeExecutionDate($ticket->fields['date'], $levels_id,
                                             $ticket->fields[$pre.'_waiting_duration']);
         if ($date != null) {
            $toadd['date']           = $date;
            $toadd[$pre.'levels_id'] = $levels_id;
            $toadd['tickets_id']     = $ticket->fields["id"];
            $levelticket             = new static::$levelticketclass();
            $levelticket->add($toadd);
         }
      }
   }


   /**
    * remove a level to do for a ticket
    *
    * @param $ticket Ticket object
    *
    * @return void
   **/
   static function deleteLevelsToDo(Ticket $ticket) {
      global $DB;

      $ticketfield = static::$prefix."levels_id_ttr";

      if ($ticket->fields[$ticketfield] > 0) {
         $levelticket = new static::$levelticketclass();
         $query = "SELECT *
                   FROM `".$levelticket::getTable()."`
                   WHERE `tickets_id` = '".$ticket->fields["id"]."'";

         foreach ($DB->request($query) as $data) {
            $levelticket->delete(['id' => $data['id']]);
         }
      }
   }


   function cleanDBonPurge() {
      global $DB;

      // Clean levels
      $classname = get_called_class();
      $fk        = getForeignKeyFieldForItemType($classname);
      $level     = new static::$levelclass();
      $level->deleteByCriteria([$fk => $this->getID()]);

      // Update tickets : clean SLA/OLA
      list($dateField, $laField) = static::getFieldNames($this->fields['type']);
      $iterator =  $DB->request([
         'SELECT' => 'id',
         'FROM'   => 'glpi_tickets',
         'WHERE'  => [$laField => $this->fields['id']]
      ]);

      if (count($iterator)) {
         $ticket = new Ticket();
         while ($data = $iterator->next()) {
            $ticket->deleteLevelAgreement($classname, $data['id'], $this->fields['type']);
         }
      }

      Rule::cleanForItemAction($this);
   }
}
GLPI version 9.4.5 API API documentation generated by ApiGen