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: 
<?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");
}

/**
 * Ticket Recurrent class
 *
 * @since 0.83
**/
class TicketRecurrent extends CommonDropdown {

   // From CommonDBTM
   public $dohistory              = true;

   // From CommonDropdown
   public $first_level_menu       = "helpdesk";
   public $second_level_menu      = "ticketrecurrent";

   public $display_dropdowntitle  = false;

   static $rightname              = 'ticketrecurrent';

   public $can_be_translated      = false;



   static function getTypeName($nb = 0) {
      return __('Recurrent tickets');
   }


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

      switch ($item->getType()) {
         case 'TicketRecurrent' :
            switch ($tabnum) {
               case 1 :
                  $item->showInfos();
                  return true;
            }
            break;
      }
      return false;
   }


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

      if (Session::haveRight('tickettemplate', READ)) {
         switch ($item->getType()) {
            case 'TicketRecurrent' :
               $ong[1] = _n('Information', 'Information', Session::getPluralNumber());
               return $ong;
         }
      }
      return '';
   }


   function defineTabs($options = []) {

      $ong = [];
      $this->addDefaultFormTab($ong);
      $this->addStandardTab(__CLASS__, $ong, $options);
      $this->addStandardTab('Log', $ong, $options);

      return $ong;
   }


   function prepareInputForAdd($input) {

      $input['next_creation_date'] = $this->computeNextCreationDate($input['begin_date'],
                                                                    $input['end_date'],
                                                                    $input['periodicity'],
                                                                    $input['create_before'],
                                                                    $input['calendars_id']);
      return $input;
   }


   function prepareInputForUpdate($input) {

      if (isset($input['begin_date'])
          && isset($input['periodicity'])
          && isset($input['create_before'])) {

         $input['next_creation_date'] = $this->computeNextCreationDate($input['begin_date'],
                                                                       $input['end_date'],
                                                                       $input['periodicity'],
                                                                       $input['create_before'],
                                                                       $input['calendars_id']);
      }
      return $input;
   }


   /**
    * Return Additional Fileds for this type
   **/
   function getAdditionalFields() {

      return [['name'  => 'is_active',
                         'label' => __('Active'),
                         'type'  => 'bool',
                         'list'  => false],
                   ['name'  => 'tickettemplates_id',
                         'label' => _n('Ticket template', 'Ticket templates', 1),
                         'type'  => 'dropdownValue',
                         'list'  => true],
                   ['name'  => 'begin_date',
                         'label' => __('Start date'),
                         'type'  => 'datetime',
                         'list'  => false],
                   ['name'  => 'end_date',
                         'label' => __('End date'),
                         'type'  => 'datetime',
                         'list'  => false],
                   ['name'  => 'periodicity',
                         'label' => __('Periodicity'),
                         'type'  => 'specific_timestamp',
                         'min'   => DAY_TIMESTAMP,
                         'step'  => DAY_TIMESTAMP,
                         'max'   => 2*MONTH_TIMESTAMP],
                   ['name'  => 'create_before',
                         'label' => __('Preliminary creation'),
                         'type'  => 'timestamp',
                         'max'   => 7*DAY_TIMESTAMP,
                         'step'  => HOUR_TIMESTAMP],
                   ['name'  => 'calendars_id',
                         'label' => _n('Calendar', 'Calendars', 1),
                         'type'  => 'dropdownValue',
                         'list'  => true],
                  ];
   }


   /**
    * @since 0.83.1
    *
    * @see CommonDropdown::displaySpecificTypeField()
   **/
   function displaySpecificTypeField($ID, $field = []) {

      switch ($field['name']) {
         case 'periodicity' :
            $possible_values = [];
            for ($i=1; $i<24; $i++) {
               $possible_values[$i*HOUR_TIMESTAMP] = sprintf(_n('%d hour', '%d hours', $i), $i);
            }
            for ($i=1; $i<=30; $i++) {
               $possible_values[$i*DAY_TIMESTAMP] = sprintf(_n('%d day', '%d days', $i), $i);
            }

            for ($i=1; $i<12; $i++) {
               $possible_values[$i.'MONTH'] = sprintf(_n('%d month', '%d months', $i), $i);
            }

            for ($i=1; $i<11; $i++) {
               $possible_values[$i.'YEAR'] = sprintf(_n('%d year', '%d years', $i), $i);
            }

            Dropdown::showFromArray($field['name'], $possible_values,
                                    ['value' => $this->fields[$field['name']]]);
            break;
      }
   }

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

      if (!is_array($values)) {
         $values = [$field => $values];
      }

      switch ($field) {
         case 'periodicity' :
            if (preg_match('/([0-9]+)MONTH/', $values[$field], $matches)) {
               return sprintf(_n('%d month', '%d months', $matches[1]), $matches[1]);
            }
            if (preg_match('/([0-9]+)YEAR/', $values[$field], $matches)) {
               return sprintf(_n('%d year', '%d years', $matches[1]), $matches[1]);
            }
            return Html::timestampToString($values[$field], false);
         break;
      }
      return parent::getSpecificValueToDisplay($field, $values, $options);
   }


   function rawSearchOptions() {
      $tab = parent::rawSearchOptions();

      $tab[] = [
         'id'                 => '11',
         'table'              => $this->getTable(),
         'field'              => 'is_active',
         'name'               => __('Active'),
         'datatype'           => 'bool'
      ];

      $tab[] = [
         'id'                 => '12',
         'table'              => 'glpi_tickettemplates',
         'field'              => 'name',
         'name'               => _n('Ticket template', 'Ticket templates', 1),
         'datatype'           => 'itemlink'
      ];

      $tab[] = [
         'id'                 => '13',
         'table'              => $this->getTable(),
         'field'              => 'begin_date',
         'name'               => __('Start date'),
         'datatype'           => 'datetime'
      ];

      $tab[] = [
         'id'                 => '17',
         'table'              => $this->getTable(),
         'field'              => 'end_date',
         'name'               => __('End date'),
         'datatype'           => 'datetime'
      ];

      $tab[] = [
         'id'                 => '15',
         'table'              => $this->getTable(),
         'field'              => 'periodicity',
         'name'               => __('Periodicity'),
         'datatype'           => 'specific'
      ];

      $tab[] = [
         'id'                 => '14',
         'table'              => $this->getTable(),
         'field'              => 'create_before',
         'name'               => __('Preliminary creation'),
         'datatype'           => 'timestamp'
      ];

      $tab[] = [
         'id'                 => '18',
         'table'              => 'glpi_calendars',
         'field'              => 'name',
         'name'               => _n('Calendar', 'Calendars', 1),
         'datatype'           => 'itemlink'
      ];

      return $tab;
   }


   /**
    * Show next creation date
    *
    * @return nothing only display
   **/
   function showInfos() {

      if (!is_null($this->fields['next_creation_date'])) {
         echo "<div class='center'>";
         //TRANS: %s is the date of next creation
         echo sprintf(__('Next creation on %s'),
                      Html::convDateTime($this->fields['next_creation_date']));
         echo "</div>";
      }
   }


   /**
    * Compute next creation date of a ticket.
    *
    * @param string         $begin_date     Begin date of the recurrent ticket in 'Y-m-d H:i:s' format.
    * @param string         $end_date       End date of the recurrent ticket in 'Y-m-d H:i:s' format,
    *                                       or 'NULL' or empty value.
    * @param string|integer $periodicity    Periodicity of creation, could be:
    *                                        - an integer corresponding to seconds,
    *                                        - a string using "/([0-9]+)(MONTH|YEAR)/" pattern.
    * @param integer        $create_before  Anticipated creation delay in seconds.
    * @param integer|null   $calendars_id   ID of the calendar to use to restrict creation to working hours,
    *                                       or 0 / null for no calendar.
    *
    * @return string  Next creation date in 'Y-m-d H:i:s' format.
    *
    * @since 0.84 $calendars_id parameter added
    */
   function computeNextCreationDate($begin_date, $end_date, $periodicity, $create_before,
                                    $calendars_id) {

      $now = time();
      $periodicity_pattern = '/([0-9]+)(MONTH|YEAR)/';

      if (false === DateTime::createFromFormat('Y-m-d H:i:s', $begin_date)) {
         // Invalid begin date.
         return 'NULL';
      }

      $has_end_date = false !== DateTime::createFromFormat('Y-m-d H:i:s', $end_date);
      if ($has_end_date && strtotime($end_date) < $now) {
         // End date is in past.
         return 'NULL';
      }

      if (!is_int($periodicity) && !preg_match('/^\d+$/', $periodicity)
          && !preg_match($periodicity_pattern, $periodicity)) {
         // Invalid periodicity.
         return 'NULL';
      }

      // Compute periodicity values
      $periodicity_as_interval = null;
      $periodicity_in_seconds = $periodicity;
      $matches = [];
      if (preg_match($periodicity_pattern, $periodicity, $matches)) {
         $periodicity_as_interval = "{$matches[1]} {$matches[2]}";
         $periodicity_in_seconds  = $matches[1]
            * MONTH_TIMESTAMP
            * ('YEAR' === $matches[2] ? 12 : 1);
      } else if ($periodicity % DAY_TIMESTAMP == 0) {
         $periodicity_as_interval = ($periodicity / DAY_TIMESTAMP) . ' DAY';
      } else {
         $periodicity_as_interval = ($periodicity / HOUR_TIMESTAMP) . ' HOUR';
      }

      // Check that anticipated creation delay is greater than periodicity.
      if ($create_before > $periodicity_in_seconds) {
         Session::addMessageAfterRedirect(
            __('Invalid frequency. It must be greater than the preliminary creation.'),
            false,
            ERROR
         );
         return 'NULL';
      }

      $calendar = new Calendar();
      if ($calendars_id && $calendar->getFromDB($calendars_id) && $calendar->hasAWorkingDay()) {
         // Base computation on calendar if calendar is defined

         $occurence_date = $calendar->computeEndDate(
            $begin_date,
            0, // 0 second delay to get the first working "second"
            0,
            false
         );
         $occurence_time = strtotime($occurence_date);
         $creation_time  = $occurence_time - $create_before;

         while ($creation_time < $now) {
            $occurence_date = $calendar->computeEndDate(
               date('Y-m-d H:i:s', $occurence_time),
               $periodicity_in_seconds,
               0,
               $periodicity_in_seconds >= DAY_TIMESTAMP
            );
            $occurence_time = strtotime($occurence_date);
            $creation_time  = $occurence_time - $create_before;

            // Stop if end date reached
            if ($has_end_date && $occurence_time > strtotime($end_date)) {
               return 'NULL';
            }
         };
      } else {
         // First occurence of creation
         $occurence_time = strtotime($begin_date);
         $creation_time  = $occurence_time - $create_before;

         // Add steps while creation time is in past
         while ($creation_time < $now) {
            $creation_time  = strtotime("+ $periodicity_as_interval", $creation_time);
            $occurence_time = $creation_time + $create_before;

            // Stop if end date reached
            if ($has_end_date && $occurence_time > strtotime($end_date)) {
               return 'NULL';
            }
         }
      }

      return date("Y-m-d H:i:s", $creation_time);
   }


   /**
    * Give cron information
    *
    * @param $name : task's name
    *
    * @return arrray of information
   **/
   static function cronInfo($name) {

      switch ($name) {
         case 'ticketrecurrent' :
            return ['description' => self::getTypeName(Session::getPluralNumber())];
      }
      return [];
   }


   /**
    * Cron for ticket's automatic close
    *
    * @param $task : crontask object
    *
    * @return integer (0 : nothing done - 1 : done)
   **/
   static function cronTicketRecurrent($task) {
      global $DB;

      $tot = 0;

      $query = "SELECT *
                FROM `glpi_ticketrecurrents`
                WHERE `glpi_ticketrecurrents`.`next_creation_date` < NOW()
                      AND `glpi_ticketrecurrents`.`is_active` = 1
                      AND (`glpi_ticketrecurrents`.`end_date` IS NULL
                           OR `glpi_ticketrecurrents`.`end_date` > NOW())";

      foreach ($DB->request($query) as $data) {
         if (self::createTicket($data)) {
            $tot++;
         } else {
            //TRANS: %s is a name
            $task->log(sprintf(__('Failed to create recurrent ticket %s'),
                               $data['name']));
         }
      }

      $task->setVolume($tot);
      return ($tot > 0 ? 1 : 0);
   }


   /**
    * Create a ticket based on ticket recurrent infos
    *
    * @param $data array data of a entry of glpi_ticketrecurrents
    *
    * @return boolean
   **/
   static function createTicket($data) {

      $result = false;
      $tt     = new TicketTemplate();

      // Create ticket based on ticket template and entity information of ticketrecurrent
      if ($tt->getFromDB($data['tickettemplates_id'])) {
         // Get default values for ticket
         $input = Ticket::getDefaultValues($data['entities_id']);
         // Apply tickettemplates predefined values
         $ttp        = new TicketTemplatePredefinedField();
         $predefined = $ttp->getPredefinedFields($data['tickettemplates_id'], true);

         if (count($predefined)) {
            foreach ($predefined as $predeffield => $predefvalue) {
               $input[$predeffield] = $predefvalue;
            }
         }
         // Set date to creation date
         $createtime    = strtotime($data['next_creation_date'])+$data['create_before'];
         $input['date'] = date('Y-m-d H:i:s', $createtime);
         if (isset($predefined['date'])) {
            $input['date'] = Html::computeGenericDateTimeSearch($predefined['date'], false,
                                                                $createtime);
         }
         // Compute time_to_resolve if predefined based on create date
         if (isset($predefined['time_to_resolve'])) {
            $input['time_to_resolve'] = Html::computeGenericDateTimeSearch($predefined['time_to_resolve'], false,
                                                                    $createtime);
         }

         // Compute internal_time_to_resolve if predefined based on create date
         if (isset($predefined['internal_time_to_resolve'])) {
            $input['internal_time_to_resolve'] = Html::computeGenericDateTimeSearch($predefined['internal_time_to_resolve'], false,
                                                                           $createtime);
         }
         // Set entity
         $input['entities_id'] = $data['entities_id'];
         $input['_auto_import'] = true;

         $ticket = new Ticket();
         $input  = Toolbox::addslashes_deep($input);
         if ($tid = $ticket->add($input)) {
            $msg = sprintf(__('Ticket %d successfully created'), $tid);
            $result = true;
         } else {
            $msg = __('Ticket creation failed (check mandatory fields)');
         }
      } else {
         $msg = __('Ticket creation failed (no template)');
      }
      $changes[0] = 0;
      $changes[1] = '';
      $changes[2] = addslashes($msg);
      Log::history($data['id'], __CLASS__, $changes, '', Log::HISTORY_LOG_SIMPLE_MESSAGE);

      // Compute next creation date
      $tr = new self();
      if ($tr->getFromDB($data['id'])) {
         $input                       = [];
         $input['id']                 = $data['id'];
         $input['next_creation_date'] = $tr->computeNextCreationDate($data['begin_date'],
                                                                     $data['end_date'],
                                                                     $data['periodicity'],
                                                                     $data['create_before'],
                                                                     $data['calendars_id']);
         $tr->update($input);
      }

      return $result;
   }

}
GLPI version 9.4.5 API API documentation generated by ApiGen