Inheritance: extends SugarBean
 /**
  * Transforms an object (contract) to a string (name).
  *
  * @param  Contract|null $entity
  * @return string
  */
 public function transform($entity)
 {
     if (null === $entity) {
         return "";
     }
     return $entity->getNumber() . ' / ' . $entity->getDoor()->getLocation() . ' / ' . $entity->getDoor()->getType();
 }
 static function pdfForItem(PluginPdfSimplePDF $pdf, CommonDBTM $item)
 {
     global $DB, $CFG_GLPIG;
     if (!Session::haveRight("contract", "r")) {
         return false;
     }
     $type = $item->getType();
     $ID = $item->getField('id');
     $con = new Contract();
     $query = "SELECT *\n                FROM `glpi_contracts_items`\n                WHERE `glpi_contracts_items`.`items_id` = '" . $ID . "'\n                      AND `glpi_contracts_items`.`itemtype` = '" . $type . "'";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $i = $j = 0;
     $pdf->setColumnsSize(100);
     if ($number > 0) {
         $pdf->displayTitle('<b>' . _N('Associated contract', 'Associated contracts', 2) . '</b>');
         $pdf->setColumnsSize(19, 19, 19, 16, 11, 16);
         $pdf->displayTitle(__('Name'), _x('phone', 'Number'), __('Contract type'), __('Supplier'), __('Start date'), __('Initial contract period'));
         $i++;
         while ($j < $number) {
             $cID = $DB->result($result, $j, "contracts_id");
             $assocID = $DB->result($result, $j, "id");
             if ($con->getFromDB($cID)) {
                 $pdf->displayLine(empty($con->fields["name"]) ? "(" . $con->fields["id"] . ")" : $con->fields["name"], $con->fields["num"], Html::clean(Dropdown::getDropdownName("glpi_contracttypes", $con->fields["contracttypes_id"])), str_replace("<br>", " ", $con->getSuppliersNames()), Html::convDate($con->fields["begin_date"]), sprintf(_n('%d month', '%d months', $con->fields["duration"]), $con->fields["duration"]));
             }
             $j++;
         }
     } else {
         $pdf->displayTitle("<b>" . __('No item found') . "</b>");
     }
     $pdf->displaySpace();
 }
 public function actionLoadContractsSampler()
 {
     if (!Group::isUserASuperAdministrator(Yii::app()->user->userModel)) {
         throw new NotSupportedException();
     }
     for ($i = 0; $i < 11; $i++) {
         $owner = Yii::app()->user->userModel;
         $name = 'Mass Delete ' . $i;
         $currencies = Currency::getAll();
         $currencyValue = new CurrencyValue();
         $currencyValue->value = 500.54;
         $currencyValue->currency = $currencies[0];
         $contract = new Contract();
         $contract->owner = $owner;
         $contract->name = $name;
         $contract->amount = $currencyValue;
         $contract->closeDate = '2011-01-01';
         //eventually fix to make correct format
         $contract->stage->value = 'Negotiating';
         $saved = $contract->save();
         if (!$saved) {
             throw new NotSupportedException();
         }
     }
 }
Example #4
0
 public function testB()
 {
     $testValue1 = 100;
     $testValue2 = 'red';
     $testValue3 = array('name' => 'John Smith', 'age' => 30);
     $contract = new Contract(array('test1' => array('data' => $testValue1, 'definition' => 'integer'), 'test2' => array('data' => $testValue2, 'definition' => array('length' => 3, 'in' => array('red', 'green', 'blue'))), 'test3' => array('data' => $testValue3, 'definition' => array('arraylist', 'element' => array('age' => array('integer', 'lessThan' => 29), 'name' => array('alpha', 'in' => array('John Doe', 'Jane Smith')))))));
     $contract->metOrThrow();
 }
Example #5
0
 public function filterByValidUser($usersData)
 {
     /* Before filtering the data, establish the agreement for the method parameters. */
     $contract = new Contract();
     $contract->term('usersData')->arraylist();
     $contract->metOrThrow();
     /* Users data must be an array of elements, each element an array itself, with an id, name, registered date, and active boolean true.
        Allowed fields to be returned are the defined elements: id, name, registered, active. */
     $contract->term('usersData')->elements()->arraylist()->element('id')->id()->end()->element('name')->optional()->alpha()->end()->element('registered')->datetime()->end()->element('active')->boolean()->equals(true)->end();
     $filteredData = $contract->term('usersData')->data();
     return $filteredData;
 }
Example #6
0
 public function createUser($userId, $userData)
 {
     /* Define Contract Requirements for Model Data */
     $contract = new Contract();
     $contract->term('userId')->id();
     $contract->term('userData')->arraylist()->element('type')->in(array('member', 'administrator'))->end()->element('username')->alphaNumeric()->length(8, 16)->end()->element('name')->required()->end()->element('address')->required()->end()->element('city')->required()->end()->element('state')->length(2)->end()->element('zip')->length(5, 10)->end()->element('country')->required()->end()->element('email')->email()->end()->element('phone')->phone()->end()->element('fax')->optional()->phone()->end()->element('photo')->optional()->file()->end()->element('website')->optional()->url()->end()->element('registered')->datetime()->end()->element('active')->boolean()->end();
     $contract->metOrThrow();
     /* Follow w/ Basic MySQL Query */
     $rows = array();
     /* $select = "SELECT * FROM user WHERE id = {$userId}";
     		while($row = mysql_query($select)) $rows[] = $row; */
     return $rows;
 }
 /**
  * Check right on an contract - overloaded to check max_links_allowed
  *
  * @param $ID ID of the item (-1 if new item)
  * @param $right Right to check : r / w / recursive
  * @param $input array of input data (used for adding item)
  *
  * @return boolean
  **/
 function can($ID, $right, &$input = NULL)
 {
     if ($ID < 0) {
         // Ajout
         $contract = new Contract();
         if (!$contract->getFromDB($input['contracts_id'])) {
             return false;
         }
         if ($contract->fields['max_links_allowed'] > 0 && countElementsInTable($this->getTable(), "`contracts_id`='" . $input['contracts_id'] . "'") >= $contract->fields['max_links_allowed']) {
             return false;
         }
     }
     return parent::can($ID, $right, $input);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     UserTestHelper::createBasicUser('jim');
     AllPermissionsOptimizationUtil::rebuild();
     ContractTestHelper::createContractStagesIfDoesNotExist();
     ContractTestHelper::createContractSourcesIfDoesNotExist();
     $currencies = Currency::getAll();
     //Make Contracts for testing chart data.
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 200;
     $currencyValue->currency = $currencies[0];
     $contract = new Contract();
     $contract->owner = $super;
     $contract->name = 'abc1';
     $contract->amount = $currencyValue;
     $contract->closeDate = '2011-01-01';
     $contract->stage->value = 'Negotiating';
     $contract->source->value = 'Outbound';
     assert($contract->save());
     // Not Coding Standard
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 350;
     $currencyValue->currency = $currencies[0];
     $contract = new Contract();
     $contract->owner = $super;
     $contract->name = 'abc2';
     $contract->amount = $currencyValue;
     $contract->closeDate = '2011-01-01';
     $contract->stage->value = 'Negotiating';
     $contract->source->value = 'Trade Show';
     assert($contract->save());
     // Not Coding Standard
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 100;
     $currencyValue->currency = $currencies[0];
     $contract = new Contract();
     $contract->owner = $super;
     $contract->name = 'abc2';
     $contract->amount = $currencyValue;
     $contract->closeDate = '2011-01-01';
     $contract->stage->value = 'Verbal';
     $contract->source->value = 'Trade Show';
     assert($contract->save());
     // Not Coding Standard
 }
 public function testSaveAndRetrievePortlet()
 {
     $user = UserTestHelper::createBasicUser('Billy');
     $contracts = Contract::getByName('superOpp');
     $portlet = new Portlet();
     $portlet->column = 2;
     $portlet->position = 5;
     $portlet->layoutId = 'Test';
     $portlet->collapsed = true;
     $portlet->viewType = 'ContractsForContactRelatedList';
     $portlet->serializedViewData = serialize(array('title' => 'Testing Title'));
     $portlet->user = $user;
     $this->assertTrue($portlet->save());
     $portlet = Portlet::getById($portlet->id);
     $params = array('controllerId' => 'test', 'relationModuleId' => 'test', 'relationModel' => $contracts[0], 'redirectUrl' => 'someRedirect');
     $portlet->params = $params;
     $unserializedViewData = unserialize($portlet->serializedViewData);
     $this->assertEquals(2, $portlet->column);
     $this->assertEquals(5, $portlet->position);
     $this->assertEquals('Testing Title', $portlet->getTitle());
     $this->assertEquals(false, $portlet->isEditable());
     $this->assertEquals('Test', $portlet->layoutId);
     //$this->assertEquals(true,                  $portlet->collapsed); //reenable once working
     $this->assertEquals('ContractsForContactRelatedList', $portlet->viewType);
     $this->assertEquals($user->id, $portlet->user->id);
     $view = $portlet->getView();
 }
Example #10
0
 /**
  * Show the central global view
  **/
 static function showGlobalView()
 {
     $showticket = haveRight("show_all_ticket", "1");
     echo "<table class='tab_cadre_central'><tr>";
     echo "<td class='top'><br>";
     echo "<table >";
     if ($showticket) {
         echo "<tr><td class='top' width='450px'>";
         Ticket::showCentralCount();
         echo "</td></tr>";
     }
     if (haveRight("contract", "r")) {
         echo "<tr><td class='top' width='450px'>";
         Contract::showCentral();
         echo "</td></tr>";
     }
     echo "</table></td>";
     if (haveRight("logs", "r")) {
         echo "<td class='top' width='450px'>";
         //Show last add events
         Event::showForUser($_SESSION["glpiname"]);
         echo "</td>";
     }
     echo "</tr></table>";
     if ($_SESSION["glpishow_jobs_at_login"] && $showticket) {
         echo "<br>";
         Ticket::showCentralNewList();
     }
 }
Example #11
0
 public function find_contract_team()
 {
     $conts = Contract::find_by_sql("SELECT * FROM contracts WHERE player={$this->id} AND expiry>" . time() . " AND term=0 ORDER BY date_of_reg DESC");
     if (isset($conts)) {
         return Team::find_by_id($conts[0]->team);
     } else {
         return NULL;
     }
 }
Example #12
0
 function del($ctx)
 {
     $id = intval($_GET['id']);
     $contract = Contract::get($id);
     if ($contract) {
         $contract->set_del();
     }
     _redirect(_list_url());
 }
Example #13
0
 /**
  * 
  * @param type $_id
  * @return \Illuminate\Http\Response Description
  */
 public function delete($_id)
 {
     $contract = Contract::find($_id);
     $response = array('status' => false, '_id' => $_id);
     if ($contract->delete()) {
         $response['status'] = true;
     }
     $headers = array('Content-type' => 'application/json');
     return \Illuminate\Http\Response::create($response, 200, $headers);
 }
 /**
  * (non-PHPdoc)
  * @see GamificationRules::scoreOnSaveModel()
  */
 public function scoreOnSaveModel(CEvent $event)
 {
     parent::scoreOnSaveModel($event);
     if (array_key_exists('value', $event->sender->stage->originalAttributeValues) && $event->sender->stage->value == Contract::getStageClosedWonValue()) {
         $scoreType = static::SCORE_TYPE_WIN_CONTRACT;
         $category = static::SCORE_CATEGORY_WIN_CONTRACT;
         $gameScore = GameScore::resolveToGetByTypeAndPerson($scoreType, Yii::app()->user->userModel);
         $gameScore->addValue();
         $saved = $gameScore->save();
         if (!$saved) {
             throw new FailedToSaveModelException();
         }
         GamePointUtil::addPointsByPointData(Yii::app()->user->userModel, static::getPointTypeAndValueDataByCategory($category));
     }
 }
Example #15
0
 public function login()
 {
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         /* Hypothetical Data */
         $loginUserEmail = $_REQUEST['email'];
         $loginUserPass = $_REQUEST['pass'];
         $loginUserIp = $_SERVER['REMOTE_ADDR'];
         $loginDateTime = date('Y-m-d H:i:s');
         try {
             $contract = new Contract();
             $contract->term('userEmail', $loginUserEmail)->email()->metOrThrow();
             $contract->term('userPass', $loginUserPass)->alphaNumeric()->length(8, 16)->metOrThrow();
             $contract->term('userIp', $loginUserPass)->ip()->metOrThrow();
             $contract->term('dateTime', $loginDateTime)->datetime()->metOrThrow();
             /* Get User For Login */
             $user = $userModel->getUser($userEmail, $userPass);
             $contract->term('user', $user)->arraylist()->element('id')->id()->end()->element('active')->equals(1)->end()->metOrThrow();
             $loginUserId = $user['id'];
             /* Proceed Safely to Model for Storage of User Login */
             $logged = $userModel->login($loginUserId, $loginUserIp, $loginDateTime);
             $contract->term('userLogged', $logged)->boolean()->equals(TRUE)->metOrThrow();
         } catch (Contract_Exception $e) {
             /* Collect error messages from contract exception */
             $messages = array();
             switch ($e->term) {
                 case 'userEmail':
                     $messages[] = 'Please enter an email address.';
                     break;
                 case 'userPass':
                     $messages[] = 'Please enter a password.';
                     break;
                 case 'userIp':
                     $messages[] = 'Please enter a valid ip address.';
                     break;
                 case 'dateTime':
                     $messages[] = 'Please enter a valid date time.';
                     break;
                 case 'user':
                     $messages[] = 'Please enter a valid user.';
                     break;
                 case 'userLogged':
                     $messages[] = 'Sorry. You could not be logged in.';
                     break;
                 default:
                     $messages[] = 'We do not get it either!';
                     break;
             }
         }
     }
 }
Example #16
0
 public static function getObject($id)
 {
     self::$db = DataBase::getDBO();
     if (self::$obj == null) {
         self::$obj = self::$db->getAllByID($id);
         self::$id = $id;
     } else {
         if (self::$id === $id) {
             return self::$obj;
         } else {
             self::$obj = self::$db->getAllByID($id);
             self::$id = $id;
         }
     }
     return self::$obj;
 }
 protected static function makeChartSqlQuery()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     $where = null;
     $selectDistinct = false;
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('Contract');
     Contract::resolveReadPermissionsOptimizationToSqlQuery(Yii::app()->user->userModel, $joinTablesAdapter, $where, $selectDistinct);
     $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
     $sumPart = "{$quote}currencyvalue{$quote}.{$quote}value{$quote} ";
     $sumPart .= "* {$quote}currencyvalue{$quote}.{$quote}ratetobase{$quote}";
     $selectQueryAdapter->addClause('customfield', 'value', 'source');
     $selectQueryAdapter->addClauseByQueryString("sum({$sumPart})", 'amount');
     $joinTablesAdapter->addFromTableAndGetAliasName('customfield', 'source_customfield_id', 'contract');
     $joinTablesAdapter->addFromTableAndGetAliasName('currencyvalue', 'amount_currencyvalue_id', 'contract');
     $groupBy = "{$quote}customfield{$quote}.{$quote}value{$quote}";
     $sql = SQLQueryUtil::makeQuery('contract', $selectQueryAdapter, $joinTablesAdapter, null, null, $where, null, $groupBy);
     return $sql;
 }
 /**
  * Print the HTML array of suppliers for this contract
  *
  * @since version 0.84
  *
  * @param $contract Contract object
  *
  * @return Nothing (HTML display)
  **/
 static function showForContract(Contract $contract)
 {
     global $DB, $CFG_GLPI;
     $instID = $contract->fields['id'];
     if (!$contract->can($instID, 'r') || !Session::haveRight("contact_enterprise", "r")) {
         return false;
     }
     $canedit = $contract->can($instID, 'w');
     $rand = mt_rand();
     $query = "SELECT `glpi_contracts_suppliers`.`id`,\n                       `glpi_suppliers`.`id` AS entID,\n                       `glpi_suppliers`.`name` AS name,\n                       `glpi_suppliers`.`website` AS website,\n                       `glpi_suppliers`.`phonenumber` AS phone,\n                       `glpi_suppliers`.`suppliertypes_id` AS type,\n                       `glpi_entities`.`id` AS entity\n                FROM `glpi_contracts_suppliers`,\n                     `glpi_suppliers`\n                LEFT JOIN `glpi_entities` ON (`glpi_entities`.`id`=`glpi_suppliers`.`entities_id`)\n                WHERE `glpi_contracts_suppliers`.`contracts_id` = '{$instID}'\n                      AND `glpi_contracts_suppliers`.`suppliers_id`=`glpi_suppliers`.`id`" . getEntitiesRestrictRequest(" AND", "glpi_suppliers", '', '', true) . "\n                ORDER BY `glpi_entities`.`completename`, `name`";
     $result = $DB->query($query);
     $suppliers = array();
     $used = array();
     if ($number = $DB->numrows($result)) {
         while ($data = $DB->fetch_assoc($result)) {
             $suppliers[$data['id']] = $data;
             $used[$data['entID']] = $data['entID'];
         }
     }
     if ($canedit) {
         echo "<div class='firstbloc'>";
         echo "<form name='contractsupplier_form{$rand}' id='contractsupplier_form{$rand}' method='post'\n                action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<input type='hidden' name='contracts_id' value='{$instID}'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add a supplier') . "</th></tr>";
         echo "<tr class='tab_bg_1'><td class='right'>";
         Supplier::dropdown(array('used' => $used, 'entity' => $contract->fields["entities_id"], 'entity_sons' => $contract->fields["is_recursive"]));
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $number) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('num_displayed' => $number);
         Html::showMassiveActions(__CLASS__, $massiveactionparams);
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     if ($canedit && $number) {
         echo "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand) . "</th>";
     }
     echo "<th>" . __('Supplier') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . __('Third party type') . "</th>";
     echo "<th>" . __('Phone') . "</th>";
     echo "<th>" . __('Website') . "</th>";
     echo "</tr>";
     $used = array();
     foreach ($suppliers as $data) {
         $ID = $data['id'];
         $website = $data['website'];
         if (!empty($website)) {
             if (!preg_match("?https*://?", $website)) {
                 $website = "http://" . $website;
             }
             $website = "<a target=_blank href='{$website}'>" . $data['website'] . "</a>";
         }
         $entID = $data['entID'];
         $entity = $data['entity'];
         $used[$entID] = $entID;
         $entname = Dropdown::getDropdownName("glpi_suppliers", $entID);
         echo "<tr class='tab_bg_1'>";
         if ($canedit) {
             echo "<td>";
             Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
             echo "</td>";
         }
         echo "<td class='center'>";
         if ($_SESSION["glpiis_ids_visible"] || empty($entname)) {
             $entname = sprintf(__('%1$s (%2$s)'), $entname, $entID);
         }
         echo "<a href='" . $CFG_GLPI["root_doc"] . "/front/supplier.form.php?id={$entID}'>" . $entname;
         echo "</a></td>";
         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $entity) . "</td>";
         echo "<td class='center'>";
         echo Dropdown::getDropdownName("glpi_suppliertypes", $data['type']) . "</td>";
         echo "<td class='center'>" . $data['phone'] . "</td>";
         echo "<td class='center'>" . $website . "</td>";
         echo "</tr>";
     }
     echo "</table>";
     if ($canedit && $number) {
         $paramsma['ontop'] = false;
         Html::showMassiveActions(__CLASS__, $paramsma);
         Html::closeForm();
     }
     echo "</div>";
 }
Example #19
0
            $html .= "</td>";
            $html .= '<td align=center><a href="' . edkuri::build(array(array('ctr_id', $ctrID, false), array('op', 'edit', false), array('sop', "del_{$type}", false), array('id', $contracttarget->getID(), false))) . '">delete</a></td></tr>';
        }
        if ($c < 30) {
            $html .= '<form id=add_target name=add_target method=post action="' . edkuri::build(array(array('ctr_id', $ctrID, false), array('op', 'edit', false))) . '">';
            $html .= "<tr><td></td></tr>";
            $html .= "<tr><td><input type=text id=add_name name=add_name size=30 maxlength=30></td><td align=center><input type=radio name=add_type id=add_type value=0 checked></td><td align=center><input type=radio name=add_type id=add_type value=1></td><td align=center><input type=radio name=add_type id=add_type value=2></td><td align=center><input type=radio name=add_type id=add_type value=3></td><td align=center><input type=submit id=submit name=submit value=Add></td></tr>";
        }
        $html .= "</table>";
        $html .= "</form>";
    }
}
// add
if (edkURI::getArg('op') == "add") {
    if ($_POST['detail_submit']) {
        $contract = new Contract();
        $contract->add($_POST['ctr_name'], $_POST['ctr_started'], $_POST['ctr_ended'], $_POST['ctr_comment']);
        header("Location: " . htmlspecialchars_decode(edkuri::build(array(array('ctr_id', $contract->getID(), false), array('op', 'edit', false)))));
    }
    $page->setTitle("Administration - Add Campaign");
    $html .= "<div class=block-header2>Details</div>";
    $html .= '<form id=detail_edit name=detail_edit method=post action="' . edkuri::build(array(array('ctr_id', $ctrID, false), array('op', 'add', false))) . '">';
    $html .= "<table class=kb-table width=98%>";
    $html .= "<tr><td width=80><b>Name:</b></td><td><input type=text name=ctr_name id=ctr_name size=40 maxlength=40></td></tr>";
    $html .= "<tr><td width=80><b>Start date:</b></td><td><input type=text name=ctr_started id=ctr_started size=10 maxlength=10 value=\"" . kbdate("Y-m-d") . "\"> (yyyy-mm-dd)</td></tr>";
    $html .= "<tr><td width-80><b>End date:</b></td><td><input type=text name=ctr_ended id=ctr_ended size=10 maxlength=10> (yyyy-mm-dd or blank)</td></tr>";
    $html .= "<tr><td><b>Comment:</b></td><td><input type='text' name='ctr_comment' size='100'/></td></tr>";
    $html .= "<tr><td></td></tr>";
    $html .= "<tr><td></td><td><input type=submit name=detail_submit value=\"Save\"></td></tr>";
    $html .= "</table>";
    $html .= "</form>";
 /**
  * Print the contract costs
  *
  * @param $contract               Contract object
  * @param $withtemplate  boolean  Template or basic item (default '')
  *
  * @return Nothing (call to classes members)
  **/
 static function showForContract(Contract $contract, $withtemplate = '')
 {
     global $DB, $CFG_GLPI;
     $ID = $contract->fields['id'];
     if (!$contract->getFromDB($ID) || !$contract->can($ID, READ)) {
         return false;
     }
     $canedit = $contract->can($ID, UPDATE);
     echo "<div class='center'>";
     $query = "SELECT *\n                FROM `glpi_contractcosts`\n                WHERE `contracts_id` = '{$ID}'\n                ORDER BY `begin_date`";
     $rand = mt_rand();
     if ($canedit) {
         echo "<div id='viewcost" . $ID . "_{$rand}'></div>\n";
         echo "<script type='text/javascript' >\n";
         echo "function viewAddCost" . $ID . "_{$rand}() {\n";
         $params = array('type' => __CLASS__, 'parenttype' => 'Contract', 'contracts_id' => $ID, 'id' => -1);
         Ajax::updateItemJsCode("viewcost" . $ID . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
         echo "};";
         echo "</script>\n";
         echo "<div class='center firstbloc'>" . "<a class='vsubmit' href='javascript:viewAddCost" . $ID . "_{$rand}();'>";
         echo __('Add a new cost') . "</a></div>\n";
     }
     if ($result = $DB->query($query)) {
         echo "<table class='tab_cadre_fixehov'>";
         echo "<tr><th colspan='5'>" . self::getTypeName($DB->numrows($result)) . "</th></tr>";
         if ($DB->numrows($result)) {
             echo "<tr><th>" . __('Name') . "</th>";
             echo "<th>" . __('Begin date') . "</th>";
             echo "<th>" . __('End date') . "</th>";
             echo "<th>" . __('Budget') . "</th>";
             echo "<th>" . __('Cost') . "</th>";
             echo "</tr>";
             Session::initNavigateListItems(__CLASS__, sprintf(__('%1$s = %2$s'), Contract::getTypeName(1), $contract->getName()));
             $total = 0;
             while ($data = $DB->fetch_assoc($result)) {
                 echo "<tr class='tab_bg_2' " . ($canedit ? "style='cursor:pointer' onClick=\"viewEditCost" . $data['contracts_id'] . "_" . $data['id'] . "_{$rand}();\"" : '') . ">";
                 $name = empty($data['name']) ? sprintf(__('%1$s (%2$s)'), $data['name'], $data['id']) : $data['name'];
                 echo "<td>";
                 printf(__('%1$s %2$s'), $name, Html::showToolTip($data['comment'], array('display' => false)));
                 if ($canedit) {
                     echo "\n<script type='text/javascript' >\n";
                     echo "function viewEditCost" . $data['contracts_id'] . "_" . $data["id"] . "_{$rand}() {\n";
                     $params = array('type' => __CLASS__, 'parenttype' => 'Contract', 'contracts_id' => $data["contracts_id"], 'id' => $data["id"]);
                     Ajax::updateItemJsCode("viewcost" . $ID . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
                     echo "};";
                     echo "</script>\n";
                 }
                 echo "</td>";
                 echo "<td>" . Html::convDate($data['begin_date']) . "</td>";
                 echo "<td>" . Html::convDate($data['end_date']) . "</td>";
                 echo "<td>" . Dropdown::getDropdownName('glpi_budgets', $data['budgets_id']) . "</td>";
                 echo "<td class='numeric'>" . Html::formatNumber($data['cost']) . "</td>";
                 $total += $data['cost'];
                 echo "</tr>";
                 Session::addToNavigateListItems(__CLASS__, $data['id']);
             }
             echo "<tr class='b noHover'><td colspan='3'>&nbsp;</td>";
             echo "<td class='right'>" . __('Total cost') . '</td>';
             echo "<td class='numeric'>" . Html::formatNumber($total) . '</td></tr>';
         } else {
             echo "<tr><th colspan='5'>" . __('No item found') . "</th></tr>";
         }
         echo "</table>";
     }
     echo "</div><br>";
 }
 /**
  * There is a special way you can import rateToBase and currencyCode for an amount attribute.
  * if the column data is formatted like: $54.67__1.2__USD  then it will split the column and properly
  * handle rate and currency code.  Eventually this will be exposed in the user interface
  */
 public function testImportWithRateAndCurrencyCodeSpecified()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $account = AccountTestHelper::createAccountByNameForOwner('Account', Yii::app()->user->userModel);
     $accountId = $account->id;
     $contracts = Contract::getAll();
     $this->assertEquals(0, count($contracts));
     $import = new Import();
     $serializedData['importRulesType'] = 'Contracts';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importTestIncludingRateAndCurrencyCode.csv', $import->getTempTableName(), true, Yii::getPathOfAlias('application.modules.contracts.tests.unit.files'));
     //update the ids of the account column to match the parent account.
     ZurmoRedBean::exec("update " . $import->getTempTableName() . " set column_3 = " . $account->id . " where id != 1 limit 4");
     $this->assertEquals(4, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $currency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
     $mappingData = array('column_0' => ImportMappingUtil::makeStringColumnMappingData('name'), 'column_1' => ImportMappingUtil::makeDateColumnMappingData('closeDate'), 'column_2' => ImportMappingUtil::makeIntegerColumnMappingData('description'), 'column_3' => ImportMappingUtil::makeHasOneColumnMappingData('account'), 'column_4' => ImportMappingUtil::makeDropDownColumnMappingData('stage'), 'column_5' => ImportMappingUtil::makeDropDownColumnMappingData('source'), 'column_6' => ImportMappingUtil::makeCurrencyColumnMappingData('amount', $currency));
     $importRules = ImportRulesUtil::makeImportRulesByType('Contracts');
     $page = 0;
     $config = array('pagination' => array('pageSize' => 50));
     //This way all rows are processed.
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     $dataProvider->getPagination()->setCurrentPage($page);
     $importResultsUtil = new ImportResultsUtil($import);
     $messageLogger = new ImportMessageLogger();
     ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, new ExplicitReadWriteModelPermissions(), $messageLogger);
     $importResultsUtil->processStatusAndMessagesForEachRow();
     //Confirm that 3 models where created.
     $contracts = Contract::getAll();
     $this->assertEquals(3, count($contracts));
     $contracts = Contract::getByName('opp1');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp1', $contracts[0]->name);
     $this->assertEquals('1980-06-03', $contracts[0]->closeDate);
     $this->assertEquals(10, $contracts[0]->probability);
     $this->assertEquals('desc1', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Prospecting', $contracts[0]->stage->value);
     $this->assertEquals('Self-Generated', $contracts[0]->source->value);
     $this->assertEquals(500, $contracts[0]->amount->value);
     $this->assertEquals(1, $contracts[0]->amount->rateToBase);
     $this->assertEquals('USD', $contracts[0]->amount->currency->code);
     $contracts = Contract::getByName('opp2');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp2', $contracts[0]->name);
     $this->assertEquals('1980-06-04', $contracts[0]->closeDate);
     $this->assertEquals(25, $contracts[0]->probability);
     $this->assertEquals('desc2', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Qualification', $contracts[0]->stage->value);
     $this->assertEquals('Inbound Call', $contracts[0]->source->value);
     $this->assertEquals(501, $contracts[0]->amount->value);
     // $this->assertEquals(2.7,                       $contracts[0]->amount->rateToBase);
     $this->assertEquals('GBP', $contracts[0]->amount->currency->code);
     $contracts = Contract::getByName('opp3');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp3', $contracts[0]->name);
     $this->assertEquals('1980-06-05', $contracts[0]->closeDate);
     $this->assertEquals(50, $contracts[0]->probability);
     $this->assertEquals('desc3', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Negotiating', $contracts[0]->stage->value);
     $this->assertEquals('Tradeshow', $contracts[0]->source->value);
     $this->assertEquals(502, $contracts[0]->amount->value);
     // $this->assertEquals(3.2,                       $contracts[0]->amount->rateToBase);
     $this->assertEquals('EUR', $contracts[0]->amount->currency->code);
     //Confirm 10 rows were processed as 'created'.
     $this->assertEquals(3, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::CREATED));
     //Confirm that 0 rows were processed as 'updated'.
     $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::UPDATED));
     //Confirm 2 rows were processed as 'errors'.
     $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR));
     $beansWithErrors = ImportDatabaseUtil::getSubset($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR);
     $this->assertEquals(0, count($beansWithErrors));
     //test the account has 3 contracts
     $account->forget();
     $account = Account::getById($accountId);
     $this->assertEquals(3, $account->contracts->count());
 }
Example #22
0
             Plugin::displayAction($monitor, $_REQUEST['glpi_tab'], $_POST["withtemplate"]);
     }
 } else {
     switch ($_REQUEST['glpi_tab']) {
         case -1:
             Computer_Item::showForItem($monitor);
             Infocom::showForItem($monitor);
             Contract::showAssociated($monitor);
             Document::showAssociated($monitor, $_POST["withtemplate"]);
             Ticket::showListForItem('Monitor', $_POST["id"]);
             Link::showForItem('Monitor', $_POST["id"]);
             Plugin::displayAction($monitor, $_REQUEST['glpi_tab']);
             break;
         case 4:
             Infocom::showForItem($monitor);
             Contract::showAssociated($monitor);
             break;
         case 5:
             Document::showAssociated($monitor, $_POST["withtemplate"]);
             break;
         case 6:
             Ticket::showListForItem('Monitor', $_POST["id"]);
             break;
         case 7:
             Link::showForItem('Monitor', $_POST["id"]);
             break;
         case 10:
             showNotesForm($_POST['target'], 'Monitor', $_POST["id"]);
             break;
         case 11:
             Reservation::showForItem('Monitor', $_POST["id"]);
 /**
  * Show report title
  **/
 static function title()
 {
     global $PLUGIN_HOOKS, $CFG_GLPI;
     // Report generation
     // Default Report included
     $report_list["default"]["name"] = __('Default report');
     $report_list["default"]["file"] = "report.default.php";
     if (Contract::canView()) {
         // Rapport ajoute par GLPI V0.2
         $report_list["Contrats"]["name"] = __('By contract');
         $report_list["Contrats"]["file"] = "report.contract.php";
     }
     if (Infocom::canView()) {
         $report_list["Par_annee"]["name"] = __('By year');
         $report_list["Par_annee"]["file"] = "report.year.php";
         $report_list["Infocoms"]["name"] = __('Hardware financial and administrative information');
         $report_list["Infocoms"]["file"] = "report.infocom.php";
         $report_list["Infocoms2"]["name"] = __('Other financial and administrative information (licenses, cartridges, consumables)');
         $report_list["Infocoms2"]["file"] = "report.infocom.conso.php";
     }
     if (Session::haveRight("networking", READ)) {
         $report_list["Rapport prises reseau"]["name"] = __('Network report');
         $report_list["Rapport prises reseau"]["file"] = "report.networking.php";
     }
     if (Session::haveRight("reservation", READ)) {
         $report_list["reservation"]["name"] = __('Loan');
         $report_list["reservation"]["file"] = "report.reservation.php";
     }
     if (Computer::canView() || Monitor::canView() || Session::haveRight("networking", READ) || Peripheral::canView() || Printer::canView() || Phone::canView()) {
         $report_list["state"]["name"] = _n('Status', 'Statuses', Session::getPluralNumber());
         $report_list["state"]["file"] = "report.state.php";
     }
     //Affichage du tableau de presentation des stats
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='2'>" . __('Select the report you want to generate') . "</th></tr>";
     echo "<tr class='tab_bg_1'><td class='center'>";
     $count = count($report_list);
     $selected = -1;
     $values = array($CFG_GLPI["root_doc"] . '/front/report.php' => Dropdown::EMPTY_VALUE);
     while ($data = each($report_list)) {
         $val = $data[0];
         $name = $report_list["{$val}"]["name"];
         $file = $report_list["{$val}"]["file"];
         $key = $CFG_GLPI["root_doc"] . "/front/" . $file;
         $values[$key] = $name;
         if (stripos($_SERVER['REQUEST_URI'], $key) !== false) {
             $selected = $key;
         }
     }
     $names = array();
     $optgroup = array();
     if (isset($PLUGIN_HOOKS["reports"]) && is_array($PLUGIN_HOOKS["reports"])) {
         foreach ($PLUGIN_HOOKS["reports"] as $plug => $pages) {
             if (is_array($pages) && count($pages)) {
                 foreach ($pages as $page => $name) {
                     $names[$plug . '/' . $page] = array("name" => $name, "plug" => $plug);
                     $optgroup[$plug] = Plugin::getInfo($plug, 'name');
                 }
             }
         }
         asort($names);
     }
     foreach ($optgroup as $opt => $title) {
         $group = $title;
         foreach ($names as $key => $val) {
             if ($opt == $val["plug"]) {
                 $file = $CFG_GLPI["root_doc"] . "/plugins/" . $key;
                 $values[$group][$file] = $val["name"];
                 if (stripos($_SERVER['REQUEST_URI'], $file) !== false) {
                     $selected = $file;
                 }
             }
         }
     }
     Dropdown::showFromArray('statmenu', $values, array('on_change' => "window.location.href=this.options[this.selectedIndex].value", 'value' => $selected));
     echo "</td>";
     echo "</tr>";
     echo "</table>";
 }
Example #24
0
 /**
  * @since version 0.84
  *
  * @param $field
  * @param $name               (default '')
  * @param $values             (default '')
  * @param $options      array
  **/
 static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = array())
 {
     global $DB;
     if (!is_array($values)) {
         $values = array($field => $values);
     }
     $options['display'] = false;
     switch ($field) {
         case 'use_licenses_alert':
         case 'use_contracts_alert':
         case 'use_infocoms_alert':
             $options['name'] = $name;
             $options['value'] = $values[$field];
             return Alert::dropdownYesNo($options);
         case 'cartridges_alert_repeat':
         case 'consumables_alert_repeat':
             $options['name'] = $name;
             $options['value'] = $values[$field];
             return Alert::dropdown($options);
         case 'send_contracts_alert_before_delay':
         case 'send_infocoms_alert_before_delay':
         case 'send_licenses_alert_before_delay':
             $options['unit'] = 'day';
             $options['never_string'] = __('No');
             return Alert::dropdownIntegerNever($name, $values[$field], $options);
         case 'use_reservations_alert':
             $options['unit'] = 'hour';
             return Alert::dropdownIntegerNever($name, $values[$field], $options);
         case 'notclosed_delay':
             $options['unit'] = 'hour';
             return Alert::dropdownIntegerNever($name, $values[$field], $options);
         case 'auto_assign_mode':
             $options['name'] = $name;
             $options['value'] = $values[$field];
             return self::dropdownAutoAssignMode($options);
         case 'tickettype':
             $options['value'] = $values[$field];
             $options['toadd'] = array(self::CONFIG_PARENT => __('Inheritance of the parent entity'));
             return Ticket::dropdownType($name, $options);
         case 'autofill_buy_date':
         case 'autofill_order_date':
         case 'autofill_delivery_date':
         case 'autofill_use_date':
             $tab[0] = __('No autofill');
             $tab[self::CONFIG_PARENT] = __('Inheritance of the parent entity');
             foreach (getAllDatasFromTable('glpi_states') as $state) {
                 $tab[Infocom::ON_STATUS_CHANGE . '_' . $state['id']] = sprintf(__('Fill when shifting to state %s'), $state['name']);
             }
             $tab[Infocom::COPY_WARRANTY_DATE] = __('Copy the start date of warranty');
             if ($field != 'autofill_buy_date') {
                 $tab[Infocom::COPY_BUY_DATE] = __('Copy the date of purchase');
                 if ($field != 'autofill_order_date') {
                     $tab[Infocom::COPY_ORDER_DATE] = __('Copy the order date');
                     if ($field != 'autofill_delivery_date') {
                         $options[Infocom::COPY_DELIVERY_DATE] = __('Copy the delivery date');
                     }
                 }
             }
             $options['value'] = $values[$field];
             return Dropdown::showFromArray($name, $tab, $options);
         case 'autofill_warranty_date':
             $tab = array(0 => __('No autofill'), Infocom::COPY_BUY_DATE => __('Copy the date of purchase'), Infocom::COPY_ORDER_DATE => __('Copy the order date'), Infocom::COPY_DELIVERY_DATE => __('Copy the delivery date'), self::CONFIG_PARENT => __('Inheritance of the parent entity'));
             $options['value'] = $values[$field];
             return Dropdown::showFromArray($name, $tab, $options);
         case 'inquest_config':
             $typeinquest = array(self::CONFIG_PARENT => __('Inheritance of the parent entity'), 1 => __('Internal survey'), 2 => __('External survey'));
             $options['value'] = $values[$field];
             return Dropdown::showFromArray($name, $typeinquest, $options);
         case 'default_contract_alert':
             $options['name'] = $name;
             $options['value'] = $values[$field];
             return Contract::dropdownAlert($options);
         case 'default_infocom_alert':
             $options['name'] = $name;
             $options['value'] = $values[$field];
             return Infocom::dropdownAlert($options);
         case 'entities_id_software':
             $options['toadd'] = array(self::CONFIG_NEVER => __('No change of entity'));
             // Keep software in PC entity
             $options['toadd'][self::CONFIG_PARENT] = __('Inheritance of the parent entity');
             return self::dropdown($options);
     }
     return parent::getSpecificValueToSelect($field, $name, $values, $options);
 }
 /**
  * Walkthrough test for synchronous download
  */
 public function testAsynchronousDownloadDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     $notificationsBeforeCount = Notification::getCount();
     $notificationMessagesBeforeCount = NotificationMessage::getCount();
     $contracts = Contract::getAll();
     if (count($contracts)) {
         foreach ($contracts as $contract) {
             $contract->delete();
         }
     }
     $contracts = array();
     for ($i = 0; $i <= ExportModule::$asynchronousThreshold + 1; $i++) {
         $contracts[] = ContractTestHelper::createContractWithAccountByNameForOwner('contract' . $i, $super, $account);
     }
     $this->setGetArray(array('Contract_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => ''));
     $this->runControllerWithRedirectExceptionAndGetUrl('contracts/default/export');
     // Start background job
     $job = new ExportJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $fileModel = $exportItems[0]->exportFileModel;
     $this->assertEquals(1, $exportItems[0]->isCompleted);
     $this->assertEquals('csv', $exportItems[0]->exportFileType);
     $this->assertEquals('contracts', $exportItems[0]->exportFileName);
     $this->assertTrue($fileModel instanceof ExportFileModel);
     $this->assertEquals($notificationsBeforeCount + 1, Notification::getCount());
     $this->assertEquals($notificationMessagesBeforeCount + 1, NotificationMessage::getCount());
     // Check export job, when many ids are selected.
     // This will probably never happen, but we need test for this case too.
     $notificationsBeforeCount = Notification::getCount();
     $notificationMessagesBeforeCount = NotificationMessage::getCount();
     // Now test case when multiple ids are selected
     $exportItems = ExportItem::getAll();
     if (count($exportItems)) {
         foreach ($exportItems as $exportItem) {
             $exportItem->delete();
         }
     }
     $selectedIds = "";
     foreach ($contracts as $contract) {
         $selectedIds .= $contract->id . ",";
         // Not Coding Standard
     }
     $this->setGetArray(array('ContractsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'name' => '', 'officePhone' => ''), 'Contract_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$selectedIds}"));
     $this->runControllerWithRedirectExceptionAndGetUrl('contracts/default/export');
     // Start background job
     $job = new ExportJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $fileModel = $exportItems[0]->exportFileModel;
     $this->assertEquals(1, $exportItems[0]->isCompleted);
     $this->assertEquals('csv', $exportItems[0]->exportFileType);
     $this->assertEquals('contracts', $exportItems[0]->exportFileName);
     $this->assertTrue($fileModel instanceof ExportFileModel);
     $this->assertEquals($notificationsBeforeCount + 1, Notification::getCount());
     $this->assertEquals($notificationMessagesBeforeCount + 1, NotificationMessage::getCount());
 }
Example #26
0
<?php

require_once 'modules/AOS_PDF_Templates/clsMsDocGenerator.php';
require_once 'modules/AOS_PDF_Templates/PDF_Lib/mpdf.php';
require_once 'modules/AOS_PDF_Templates/templateParser.php';
require_once 'modules/AOS_PDF_Templates/sendEmail.php';
require_once 'modules/AOS_PDF_Templates/AOS_PDF_Templates.php';
global $mod_strings;
$module_type = $_REQUEST['module'];
$module = new Contract();
$module_type_file = strtoupper(ltrim(rtrim($module_type, 's'), ''));
$module_type_low = strtolower($module_type);
$module->retrieve($_REQUEST['contractid']);
$task = $_REQUEST['task'];
$doc = new clsMsDocGenerator();
$contractvalue = array();
$sql = "SELECT * FROM contract_values WHERE contract_value_id ='" . $module->id . "'and deleted = 0";
$res = $module->db->query($sql);
while ($row = $module->db->fetchByAssoc($res)) {
    $contractvalue[$row['id']] = $row['contract_value_id'];
}
$contract_condition = array();
$sql1 = "SELECT * FROM contract_conditions WHERE contract_condition_id ='" . $module->id . "' AND deleted = 0";
$res1 = $module->db->query($sql1);
while ($row1 = $module->db->fetchByAssoc($res1)) {
    $contract_condition[$row1['id']] = $row1['contract_condition_id'];
}
$transport_contract = array();
$sql2 = "SELECT * FROM transportcontracts WHERE contract_id='" . $this->id . "' AND deleted =0";
$res2 = $module->db->query($sql2);
while ($row2 = $module->db->fetchByAssoc($res2)) {
        }
    }
} else {
    switch ($_REQUEST['glpi_tab']) {
        case -1:
            NetworkPort::showForItem('NetworkEquipment', $_POST["id"]);
            Infocom::showForItem($netdevice);
            Contract::showAssociated($netdevice);
            Document::showAssociated($netdevice, $_POST["withtemplate"]);
            Ticket::showListForItem('NetworkEquipment', $_POST["id"]);
            Link::showForItem('NetworkEquipment', $_POST["id"]);
            Plugin::displayAction($netdevice, $_REQUEST['glpi_tab']);
            break;
        case 4:
            Infocom::showForItem($netdevice);
            Contract::showAssociated($netdevice);
            break;
        case 5:
            Document::showAssociated($netdevice, $_POST["withtemplate"]);
            break;
        case 6:
            Ticket::showListForItem('NetworkEquipment', $_POST["id"]);
            break;
        case 7:
            Link::showForItem('NetworkEquipment', $_POST["id"]);
            break;
        case 10:
            showNotesForm($_POST['target'], 'NetworkEquipment', $_POST["id"]);
            break;
        case 11:
            Reservation::showForItem('NetworkEquipment', $_POST["id"]);
Example #28
0
 /**
  * Get the SEARCH_OPTION array
  *
  * @param $itemtype
  * @param $withplugins boolean get search options from plugins (true by default)
  *
  * @return the reference to  array of search options for the given item type
  **/
 static function &getOptions($itemtype, $withplugins = true)
 {
     global $CFG_GLPI;
     static $search = array();
     $item = NULL;
     if (!isset($search[$itemtype])) {
         // standard type first
         switch ($itemtype) {
             case 'Internet':
                 $search[$itemtype]['common'] = __('Characteristics');
                 $search[$itemtype][1]['table'] = 'networkport_types';
                 $search[$itemtype][1]['field'] = 'name';
                 $search[$itemtype][1]['name'] = __('Name');
                 $search[$itemtype][1]['datatype'] = 'itemlink';
                 $search[$itemtype][1]['searchtype'] = 'contains';
                 $search[$itemtype][2]['table'] = 'networkport_types';
                 $search[$itemtype][2]['field'] = 'id';
                 $search[$itemtype][2]['name'] = __('ID');
                 $search[$itemtype][2]['searchtype'] = 'contains';
                 $search[$itemtype][31]['table'] = 'glpi_states';
                 $search[$itemtype][31]['field'] = 'completename';
                 $search[$itemtype][31]['name'] = __('Status');
                 $search[$itemtype] += NetworkPort::getSearchOptionsToAdd('networkport_types');
                 break;
             case 'AllAssets':
                 $search[$itemtype]['common'] = __('Characteristics');
                 $search[$itemtype][1]['table'] = 'asset_types';
                 $search[$itemtype][1]['field'] = 'name';
                 $search[$itemtype][1]['name'] = __('Name');
                 $search[$itemtype][1]['datatype'] = 'itemlink';
                 $search[$itemtype][1]['searchtype'] = 'contains';
                 $search[$itemtype][2]['table'] = 'asset_types';
                 $search[$itemtype][2]['field'] = 'id';
                 $search[$itemtype][2]['name'] = __('ID');
                 $search[$itemtype][2]['searchtype'] = 'contains';
                 $search[$itemtype][31]['table'] = 'glpi_states';
                 $search[$itemtype][31]['field'] = 'completename';
                 $search[$itemtype][31]['name'] = __('Status');
                 $search[$itemtype] += Location::getSearchOptionsToAdd();
                 $search[$itemtype][5]['table'] = 'asset_types';
                 $search[$itemtype][5]['field'] = 'serial';
                 $search[$itemtype][5]['name'] = __('Serial number');
                 $search[$itemtype][6]['table'] = 'asset_types';
                 $search[$itemtype][6]['field'] = 'otherserial';
                 $search[$itemtype][6]['name'] = __('Inventory number');
                 $search[$itemtype][16]['table'] = 'asset_types';
                 $search[$itemtype][16]['field'] = 'comment';
                 $search[$itemtype][16]['name'] = __('Comments');
                 $search[$itemtype][16]['datatype'] = 'text';
                 $search[$itemtype][70]['table'] = 'glpi_users';
                 $search[$itemtype][70]['field'] = 'name';
                 $search[$itemtype][70]['name'] = __('User');
                 $search[$itemtype][7]['table'] = 'asset_types';
                 $search[$itemtype][7]['field'] = 'contact';
                 $search[$itemtype][7]['name'] = __('Alternate username');
                 $search[$itemtype][7]['datatype'] = 'string';
                 $search[$itemtype][8]['table'] = 'asset_types';
                 $search[$itemtype][8]['field'] = 'contact_num';
                 $search[$itemtype][8]['name'] = __('Alternate username number');
                 $search[$itemtype][8]['datatype'] = 'string';
                 $search[$itemtype][71]['table'] = 'glpi_groups';
                 $search[$itemtype][71]['field'] = 'completename';
                 $search[$itemtype][71]['name'] = __('Group');
                 $search[$itemtype][19]['table'] = 'asset_types';
                 $search[$itemtype][19]['field'] = 'date_mod';
                 $search[$itemtype][19]['name'] = __('Last update');
                 $search[$itemtype][19]['datatype'] = 'datetime';
                 $search[$itemtype][19]['massiveaction'] = false;
                 $search[$itemtype][23]['table'] = 'glpi_manufacturers';
                 $search[$itemtype][23]['field'] = 'name';
                 $search[$itemtype][23]['name'] = __('Manufacturer');
                 $search[$itemtype][24]['table'] = 'glpi_users';
                 $search[$itemtype][24]['field'] = 'name';
                 $search[$itemtype][24]['linkfield'] = 'users_id_tech';
                 $search[$itemtype][24]['name'] = __('Technician in charge of the hardware');
                 $search[$itemtype][80]['table'] = 'glpi_entities';
                 $search[$itemtype][80]['field'] = 'completename';
                 $search[$itemtype][80]['name'] = __('Entity');
                 break;
             default:
                 if ($item = getItemForItemtype($itemtype)) {
                     $search[$itemtype] = $item->getSearchOptions();
                 }
                 break;
         }
         if (Session::getLoginUserID() && in_array($itemtype, $CFG_GLPI["ticket_types"])) {
             $search[$itemtype]['tracking'] = __('Assistance');
             $search[$itemtype][60]['table'] = 'glpi_tickets';
             $search[$itemtype][60]['field'] = 'id';
             $search[$itemtype][60]['datatype'] = 'count';
             $search[$itemtype][60]['name'] = _x('quantity', 'Number of tickets');
             $search[$itemtype][60]['forcegroupby'] = true;
             $search[$itemtype][60]['usehaving'] = true;
             $search[$itemtype][60]['massiveaction'] = false;
             $search[$itemtype][60]['joinparams'] = array('beforejoin' => array('table' => 'glpi_items_tickets', 'joinparams' => array('jointype' => 'itemtype_item')), 'condition' => getEntitiesRestrictRequest('AND', 'NEWTABLE'));
             $search[$itemtype][140]['table'] = 'glpi_problems';
             $search[$itemtype][140]['field'] = 'id';
             $search[$itemtype][140]['datatype'] = 'count';
             $search[$itemtype][140]['name'] = _x('quantity', 'Number of problems');
             $search[$itemtype][140]['forcegroupby'] = true;
             $search[$itemtype][140]['usehaving'] = true;
             $search[$itemtype][140]['massiveaction'] = false;
             $search[$itemtype][140]['joinparams'] = array('beforejoin' => array('table' => 'glpi_items_problems', 'joinparams' => array('jointype' => 'itemtype_item')), 'condition' => getEntitiesRestrictRequest('AND', 'NEWTABLE'));
         }
         if (in_array($itemtype, $CFG_GLPI["networkport_types"]) || $itemtype == 'AllAssets') {
             $search[$itemtype] += NetworkPort::getSearchOptionsToAdd($itemtype);
         }
         if (in_array($itemtype, $CFG_GLPI["contract_types"]) || $itemtype == 'AllAssets') {
             $search[$itemtype] += Contract::getSearchOptionsToAdd();
         }
         if (Document::canApplyOn($itemtype) || $itemtype == 'AllAssets') {
             $search[$itemtype] += Document::getSearchOptionsToAdd();
         }
         if (InfoCom::canApplyOn($itemtype) || $itemtype == 'AllAssets') {
             $search[$itemtype] += Infocom::getSearchOptionsToAdd($itemtype);
         }
         if (in_array($itemtype, $CFG_GLPI["link_types"])) {
             $search[$itemtype]['link'] = _n('External link', 'External links', Session::getPluralNumber());
             $search[$itemtype] += Link::getSearchOptionsToAdd($itemtype);
         }
         if ($withplugins) {
             // Search options added by plugins
             $plugsearch = Plugin::getAddSearchOptions($itemtype);
             if (count($plugsearch)) {
                 $search[$itemtype] += array('plugins' => _n('Plugin', 'Plugins', Session::getPluralNumber()));
                 $search[$itemtype] += $plugsearch;
             }
         }
         // Complete linkfield if not define
         if (is_null($item)) {
             // Special union type
             $itemtable = $CFG_GLPI['union_search_type'][$itemtype];
         } else {
             if ($item = getItemForItemtype($itemtype)) {
                 $itemtable = $item->getTable();
             }
         }
         foreach ($search[$itemtype] as $key => $val) {
             if (!is_array($val)) {
                 // skip sub-menu
                 continue;
             }
             // Compatibility before 0.80 : Force massive action to false if linkfield is empty :
             if (isset($val['linkfield']) && empty($val['linkfield'])) {
                 $search[$itemtype][$key]['massiveaction'] = false;
             }
             // Set default linkfield
             if (!isset($val['linkfield']) || empty($val['linkfield'])) {
                 if (strcmp($itemtable, $val['table']) == 0 && (!isset($val['joinparams']) || count($val['joinparams']) == 0)) {
                     $search[$itemtype][$key]['linkfield'] = $val['field'];
                 } else {
                     $search[$itemtype][$key]['linkfield'] = getForeignKeyFieldForTable($val['table']);
                 }
             }
             // Set default datatype
             //             if (!isset($val['datatype']) || empty($val['datatype'])) {
             //                if ((strcmp($itemtable,$val['table']) != 0)
             //                    && ($val['field'] == 'name' || $val['field'] == 'completename')) {
             //                   $search[$itemtype][$key]['datatype'] = 'dropdown';
             //                } else {
             //                   $search[$itemtype][$key]['datatype'] = 'string';
             //                }
             //             }
             // Add default joinparams
             if (!isset($val['joinparams'])) {
                 $search[$itemtype][$key]['joinparams'] = array();
             }
         }
     }
     return $search[$itemtype];
 }
 /**
  * Transfer contracts
  *
  * @param $itemtype original type of transfered item
  * @param $ID original ID of the contract
  * @param $newID new ID of the contract
  **/
 function transferContracts($itemtype, $ID, $newID)
 {
     global $DB;
     $need_clean_process = false;
     // if keep
     if ($this->options['keep_contract']) {
         $contract = new Contract();
         // Get contracts for the item
         $query = "SELECT *\n                   FROM `glpi_contracts_items`\n                   WHERE `items_id` = '{$ID}'\n                         AND `itemtype` = '{$itemtype}'\n                         AND `contracts_id` NOT IN " . $this->item_recurs['Contract'];
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result) > 0) {
                 // Foreach get item
                 while ($data = $DB->fetch_array($result)) {
                     $need_clean_process = false;
                     $item_ID = $data['contracts_id'];
                     $newcontractID = -1;
                     // is already transfer ?
                     if (isset($this->already_transfer['Contract'][$item_ID])) {
                         $newcontractID = $this->already_transfer['Contract'][$item_ID];
                         if ($newcontractID != $item_ID) {
                             $need_clean_process = true;
                         }
                     } else {
                         // No
                         // Can be transfer without copy ? = all linked items need to be transfer (so not copy)
                         $canbetransfer = true;
                         $query = "SELECT DISTINCT `itemtype`\n                               FROM `glpi_contracts_items`\n                               WHERE `contracts_id` = '{$item_ID}'";
                         if ($result_type = $DB->query($query)) {
                             if ($DB->numrows($result_type) > 0) {
                                 while (($data_type = $DB->fetch_array($result_type)) && $canbetransfer) {
                                     $dtype = $data_type['itemtype'];
                                     if (isset($this->item_search[$dtype])) {
                                         // No items to transfer -> exists links
                                         $query_search = "SELECT count(*) AS CPT\n                                                  FROM `glpi_contracts_items`\n                                                  WHERE `contracts_id` = '{$item_ID}'\n                                                        AND `itemtype` = '{$dtype}'\n                                                        AND `items_id`\n                                                             NOT IN " . $this->item_search[$dtype];
                                         $result_search = $DB->query($query_search);
                                         if ($DB->result($result_search, 0, 'CPT') > 0) {
                                             $canbetransfer = false;
                                         }
                                     } else {
                                         $canbetransfer = false;
                                     }
                                 }
                             }
                         }
                         // Yes : transfer
                         if ($canbetransfer) {
                             $this->transferItem('Contract', $item_ID, $item_ID);
                             $newcontractID = $item_ID;
                         } else {
                             $need_clean_process = true;
                             $contract->getFromDB($item_ID);
                             // No : search contract
                             $query = "SELECT *\n                                  FROM `glpi_contracts`\n                                  WHERE `entities_id` = '" . $this->to . "'\n                                        AND `name` = '" . addslashes($contract->fields['name']) . "'";
                             if ($result_search = $DB->query($query)) {
                                 if ($DB->numrows($result_search) > 0) {
                                     $newcontractID = $DB->result($result_search, 0, 'id');
                                     $this->addToAlreadyTransfer('Contract', $item_ID, $newcontractID);
                                 }
                             }
                             // found : use it
                             // not found : copy contract
                             if ($newcontractID < 0) {
                                 // 1 - create new item
                                 unset($contract->fields['id']);
                                 $input = $contract->fields;
                                 $input['entities_id'] = $this->to;
                                 unset($contract->fields);
                                 $newcontractID = $contract->add($input);
                                 // 2 - transfer as copy
                                 $this->transferItem('Contract', $item_ID, $newcontractID);
                             }
                         }
                     }
                     // Update links
                     if ($ID == $newID) {
                         if ($item_ID != $newcontractID) {
                             $query = "UPDATE `glpi_contracts_items`\n                                  SET `contracts_id` = '{$newcontractID}'\n                                  WHERE `id` = '" . $data['id'] . "'";
                             $DB->query($query);
                         }
                         // Same Item -> update links
                     } else {
                         // Copy Item -> copy links
                         if ($item_ID != $newcontractID) {
                             $query = "INSERT\n                                  INTO `glpi_contracts_items`\n                                  (`contracts_id`, `items_id`, `itemtype`)\n                                  VALUES ('{$newcontractID}', '{$newID}', '{$itemtype}')";
                             $DB->query($query);
                         } else {
                             // same contract for new item update link
                             $query = "UPDATE `glpi_contracts_items`\n                                  SET `items_id` = '{$newID}'\n                                  WHERE `id` = '" . $data['id'] . "'";
                             $DB->query($query);
                         }
                     }
                     // If clean and unused ->
                     if ($need_clean_process && $this->options['clean_contract']) {
                         $query = "SELECT COUNT(*) AS CPT\n                               FROM `glpi_contracts_items`\n                               WHERE `contracts_id` = '{$item_ID}'";
                         if ($result_remaining = $DB->query($query)) {
                             if ($DB->result($result_remaining, 0, 'CPT') == 0) {
                                 if ($this->options['clean_contract'] == 1) {
                                     $contract->delete(array('id' => $item_ID));
                                 }
                                 if ($this->options['clean_contract'] == 2) {
                                     // purge
                                     $contract->delete(array('id' => $item_ID), 1);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     } else {
         // else unlink
         $query = "DELETE\n                   FROM `glpi_contracts_items`\n                   WHERE `items_id` = '{$ID}'\n                         AND `itemtype` = '{$itemtype}'";
         $DB->query($query);
     }
 }
Example #30
0
<?php

if (!defined('sugarEntry') || !sugarEntry) {
    die('Not A Valid Entry Point');
}
require_once 'modules/Contracts/Contract.php';
require_once 'include/formbase.php';
require_once 'modules/ContractConditions/ContractCondition.php';
require_once 'modules/ContractValues/ContractValue.php';
require_once 'modules/TransportContracts/TransportContracts.php';
require_once 'modules/FITs/CustomerRating.php';
include "config.php";
global $sugar_config;
$focus = new Contract();
$focus->retrieve($_POST['record']);
if (!$focus->ACLAccess('Save')) {
    ACLController::displayNoAccess(true);
    sugar_cleanup(true);
}
if (!empty($_POST['assigned_user_id']) && $focus->assigned_user_id != $_POST['assigned_user_id'] && $_POST['assigned_user_id'] != $current_user->id) {
    $check_notify = TRUE;
} else {
    $check_notify = FALSE;
}
foreach ($focus->column_fields as $field) {
    if (isset($_POST[$field])) {
        $value = $_POST[$field];
        switch ($field) {
            case 'template_ddown_c':
                $value = implode("^,^", $_POST[$field]);
                break;