public function isValid($value)
 {
     if (!parent::isValid($value)) {
         return false;
     }
     // Not a number
     if (!empty($value) && !is_numeric($value)) {
         Session::addMessageAfterRedirect(__('This is not a number:', 'formcreator') . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // Min range not set or text length longer than min length
     } elseif (!empty($this->fields['range_min']) && $value < $this->fields['range_min']) {
         $message = sprintf(__('The following number must be greater than %d:', 'formcreator'), $this->fields['range_min']);
         Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // Max range not set or text length shorter than max length
     } elseif (!empty($this->fields['range_max']) && $value > $this->fields['range_max']) {
         $message = sprintf(__('The following number must be lower than %d:', 'formcreator'), $this->fields['range_max']);
         Session::addMessageAfterRedirect($message . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // Specific format not set or well match
     } elseif (!empty($this->fields['regex']) && !preg_match($this->fields['regex'], $value)) {
         Session::addMessageAfterRedirect(__('Specific format does not match:', 'formcreator') . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // All is OK
     } else {
         return true;
     }
 }
Example #2
0
/**
 * Plugin uninstall process
 *
 * @return boolean
 */
function plugin_fields_uninstall()
{
    global $DB;
    if (!class_exists('PluginFieldsProfile')) {
        Session::addMessageAfterRedirect(__("The plugin can't be uninstalled when the plugin is disabled", 'fields'), true, WARNING, true);
        return false;
    }
    $_SESSION['uninstall_fields'] = true;
    echo "<center>";
    echo "<table class='tab_cadre_fixe'>";
    echo "<tr><th>" . __("MySQL tables uninstallation", "fields") . "<th></tr>";
    echo "<tr class='tab_bg_1'>";
    echo "<td align='center'>";
    $classesToUninstall = array('PluginFieldsDropdown', 'PluginFieldsContainer', 'PluginFieldsContainer_Field', 'PluginFieldsLabelTranslation', 'PluginFieldsField', 'PluginFieldsValue', 'PluginFieldsProfile', 'PluginFieldsMigration');
    foreach ($classesToUninstall as $class) {
        if ($plug = isPluginItemType($class)) {
            $dir = GLPI_ROOT . "/plugins/fields/inc/";
            $item = strtolower($plug['class']);
            if (file_exists("{$dir}{$item}.class.php")) {
                include_once "{$dir}{$item}.class.php";
                if (!call_user_func(array($class, 'uninstall'))) {
                    return false;
                }
            }
        }
    }
    echo "</td>";
    echo "</tr>";
    echo "</table></center>";
    unset($_SESSION['uninstall_fields']);
    // clean display preferences
    $DB->query("DELETE FROM glpi_displaypreferences WHERE itemtype LIKE 'PluginFields%'");
    return true;
}
 static function beforeUpdate(Problem $problem)
 {
     if (!is_array($problem->input) || !count($problem->input)) {
         // Already cancel by another plugin
         return false;
     }
     //    Toolbox::logDebug("PluginBehaviorsProblem::beforeUpdate(), Problem=", $problem);
     $config = PluginBehaviorsConfig::getInstance();
     // Check is the connected user is a tech
     if (!is_numeric(Session::getLoginUserID(false)) || !Session::haveRight('problem', UPDATE)) {
         return false;
         // No check
     }
     $soltyp = isset($problem->input['solutiontypes_id']) ? $problem->input['solutiontypes_id'] : $problem->fields['solutiontypes_id'];
     // Wand to solve/close the problem
     if (isset($problem->input['solutiontypes_id']) && $problem->input['solutiontypes_id'] || isset($problem->input['solution']) && $problem->input['solution'] || isset($problem->input['status']) && in_array($problem->input['status'], array_merge(Problem::getSolvedStatusArray(), Problem::getClosedStatusArray()))) {
         if ($config->getField('is_problemsolutiontype_mandatory')) {
             if (!$soltyp) {
                 unset($problem->input['status']);
                 unset($problem->input['solution']);
                 unset($problem->input['solutiontypes_id']);
                 Session::addMessageAfterRedirect(__('You cannot close a problem without solution type', 'behaviors'), true, ERROR);
             }
         }
     }
 }
 public function isValid($value)
 {
     $value = json_decode($value);
     if (is_null($value)) {
         $value = array();
     }
     // If the field is required it can't be empty
     if ($this->isRequired() && empty($value)) {
         Session::addMessageAfterRedirect(__('A required field is empty:', 'formcreator') . ' ' . $this->getLabel(), false, ERROR);
         return false;
         // Min range not set or number of selected item lower than min
     } elseif (!empty($this->fields['range_min']) && count($value) < $this->fields['range_min']) {
         $message = sprintf(__('The following question needs of at least %d answers', 'formcreator'), $this->fields['range_min']);
         Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR);
         return false;
         // Max range not set or number of selected item greater than max
     } elseif (!empty($this->fields['range_max']) && count($value) > $this->fields['range_max']) {
         $message = sprintf(__('The following question does not accept more than %d answers', 'formcreator'), $this->fields['range_max']);
         Session::addMessageAfterRedirect($message . ' ' . $this->getLabel(), false, ERROR);
         return false;
         // All is OK
     } else {
         return true;
     }
 }
Example #5
0
 public function prepareInputForAdd($input)
 {
     if (!isset($input["number"]) || $input["number"] == '') {
         Session::addMessageAfterRedirect(__("A bill number is mandatory", "order"), false, ERROR);
         return array();
     }
     return $input;
 }
Example #6
0
 /**
  * allow to control data before updating in bdd
  *
  * @param datas $input
  * @return array|datas|the
  */
 function prepareInputForUpdate($input)
 {
     if (!isset($input["plugin_resources_professions_id"]) || $input["plugin_resources_professions_id"] == '0') {
         Session::addMessageAfterRedirect(__('The profession for the budget must be filled', 'resources'), false, ERROR);
         return array();
     }
     return $input;
 }
Example #7
0
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI, $LANG;
     if (empty($input['name'])) {
         Session::addMessageAfterRedirect($LANG['plugin_formcreator']["error_form"][5], false, ERROR);
         return false;
     }
     return $input;
 }
Example #8
0
 function pre_deleteItem()
 {
     if ($this->getID() <= self::CANCELED) {
         Session::addMessageAfterRedirect(__("You cannot remove this status", "order") . ": " . $this->fields['name'], false, ERROR);
         return false;
     } else {
         return true;
     }
 }
function plugin_news_uninstall()
{
    if (!PluginNewsAlert::dropTable() || !PluginNewsProfile::dropTable()) {
        Session::addMessageAfterRedirect('Uninstallation failed');
        return false;
    }
    PluginNewsProfile::uninstallProfile();
    return true;
}
Example #10
0
 function prepareInputForAdd($input)
 {
     // TODO: check if the entities should not be inherited from the profile or the user
     if (!isset($input['entities_id']) || $input['entities_id'] < 0) {
         Session::addMessageAfterRedirect(__('No selected element or badly defined operation'), false, ERROR);
         return false;
     }
     return parent::prepareInputForAdd($input);
 }
Example #11
0
 function prepareInputForAdd($input)
 {
     // Check override of segment : do not add
     if (count(self::getSegmentsBetween($input['calendars_id'], $input['day'], $input['begin'], $input['day'], $input['end'])) > 0) {
         Session::addMessageAfterRedirect(__('Can not add a range riding an existing period'), false, ERROR);
         return false;
     }
     return parent::prepareInputForAdd($input);
 }
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI;
     if (empty($input['name'])) {
         Session::addMessageAfterRedirect(__('Tu Ticket Target no tiene Nombre.'), false, ERROR);
         return false;
     }
     return $input;
 }
function plugin_databreakdown_install()
{
    if (!file_exists(c\DOC_DIR)) {
        $ok = mkdir(c\DOC_DIR, 0777, true);
        if (!$ok) {
            $msg = sprintf(p\__("Failed to create the plugin's document directory '%s'"), p\DOC_DIR);
            Session::addMessageAfterRedirect($msg, true, ERROR);
        }
    }
    return true;
}
Example #14
0
 static function install(Migration $migration)
 {
     //check if "inc", "front" and "ajax" directories are writeable for httpd
     $directories = array("../plugins/fields/inc", "../plugins/fields/front", "../plugins/fields/ajax");
     foreach ($directories as $directory) {
         if (!is_writable($directory)) {
             Session::addMessageAfterRedirect(__("This plugin need write right on his own files, please correct.", 'fields'), false, ERROR);
             return false;
         }
     }
     return true;
 }
 public function isValid($value)
 {
     if (!parent::isValid($value)) {
         return false;
     }
     // Specific format not set or well match
     if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
         Session::addMessageAfterRedirect(__('This is not a valid e-mail:', 'formcreator') . ' ' . $this->getLabel(), false, ERROR);
         return false;
     }
     // All is OK
     return true;
 }
Example #16
0
 public function isValid($value)
 {
     // If the field is not visible, don't check it's value
     if (!PluginFormcreatorFields::isVisible($this->fields['id'], $this->fields['answer'])) {
         return true;
     }
     // If the field is required it can't be empty
     if ($this->isRequired() && empty($value)) {
         Session::addMessageAfterRedirect(__('A required field is empty:', 'formcreator') . ' ' . $this->getLabel(), false, ERROR);
         return false;
     }
     // All is OK
     return true;
 }
 public function isValid($value)
 {
     // If the field is not visible, don't check it's value
     if (!PluginFormcreatorFields::isVisible($this->fields['id'], $this->fields['answer'])) {
         return true;
     }
     // If the field is required it can't be empty
     if ($this->isRequired() && (empty($_FILES['formcreator_field_' . $this->fields['id']]['tmp_name']) || !is_file($_FILES['formcreator_field_' . $this->fields['id']]['tmp_name']))) {
         Session::addMessageAfterRedirect(__('A required file is missing:', 'formcreator') . ' ' . $this->fields['name'], false, ERROR);
         return false;
     }
     // All is OK
     return true;
 }
Example #18
0
function plugin_themes_install_types($types = array(), $action = "install")
{
    foreach ($types as $type) {
        require_once "inc/{$type}.class.php";
        $classname = "PluginThemes" . ucfirst($type);
        if (method_exists($classname, $action)) {
            $result = call_user_func(array($classname, $action));
            if (!$result['success']) {
                Session::addMessageAfterRedirect($result['msg']);
                return false;
            }
        }
    }
    return true;
}
 function prepareInputForUpdate($input)
 {
     if (!isset($input["date_begin"]) || $input["date_begin"] == 'NULL') {
         Session::addMessageAfterRedirect(__('The begin date of the forced holiday period must be filled', 'resources'), false, ERROR);
         return array();
     }
     if (!isset($input["date_end"]) || $input["date_end"] == 'NULL') {
         Session::addMessageAfterRedirect(__('The end date of the forced holiday period must be filled', 'resources'), false, ERROR);
         return array();
     }
     //unset($input['picture']);
     $this->getFromDB($input["id"]);
     $input["_old_date_begin"] = $this->fields["date_begin"];
     $input["_old_date_end"] = $this->fields["date_end"];
     $input["_old_comment"] = $this->fields["comment"];
     return $input;
 }
Example #20
0
 /**
  * \brief Prepare the input before adding or updating
  * Checking suppose that each FQDN is compose of dot separated array of labels and its unique
  * \see (FQDNLabel)
  *
  * @param $input fields of the record to check
  *
  * @return false or fields checks and update (lowercase for the fqdn field)
  **/
 function prepareInput($input)
 {
     if (isset($input['fqdn']) || $this->isNewID($this->getID())) {
         // Check that FQDN is not empty
         if (empty($input['fqdn'])) {
             Session::addMessageAfterRedirect(__('FQDN must not be empty'), false, ERROR);
             return false;
         }
         // Transform it to lower case
         $input["fqdn"] = strtolower($input['fqdn']);
         // Then check its validity
         if (!self::checkFQDN($input["fqdn"])) {
             Session::addMessageAfterRedirect(__('FQDN is not valid'), false, ERROR);
             return false;
         }
     }
     return $input;
 }
 function prepareInputForUpdate($input)
 {
     if (!isset($input["date_begin"]) || $input["date_begin"] == 'NULL') {
         Session::addMessageAfterRedirect(__('The begin date of the non contract period must be filled', 'resources'), false, ERROR);
         return array();
     }
     if (isset($input['date_end']) && empty($input['date_end'])) {
         $input['date_end'] = 'NULL';
     }
     //unset($input['picture']);
     $this->getFromDB($input["id"]);
     $input["_old_date_begin"] = $this->fields["date_begin"];
     $input["_old_date_end"] = $this->fields["date_end"];
     $input["_old_locations_id"] = $this->fields["locations_id"];
     $input["_old_at_home"] = $this->fields["at_home"];
     $input["_old_comment"] = $this->fields["comment"];
     return $input;
 }
 public function isValid($value)
 {
     if (!parent::isValid($value)) {
         return false;
     }
     // Min range not set or text length longer than min length
     if (!empty($this->fields['range_min']) && strlen($value) < $this->fields['range_min']) {
         Session::addMessageAfterRedirect(sprintf(__('The text is too short (minimum %d characters):', 'formcreator'), $this->fields['range_min']) . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // Max range not set or text length shorter than max length
     } elseif (!empty($this->fields['range_max']) && strlen($value) > $this->fields['range_max']) {
         Session::addMessageAfterRedirect(sprintf(__('The text is too long (maximum %d characters):', 'formcreator'), $this->fields['range_max']) . ' ' . $this->fields['name'], false, ERROR);
         return false;
         // Specific format not set or well match
     } elseif (!empty($this->fields['regex']) && !preg_match($this->fields['regex'], $value)) {
         Session::addMessageAfterRedirect(__('Specific format does not match:', 'formcreator') . ' ' . $this->fields['name'], false, ERROR);
         return false;
     }
     // All is OK
     return true;
 }
Example #23
0
if (!isset($_GET['id'])) {
    $_GET['id'] = "";
}
//LDAP Server add/update/delete
if (isset($_POST["update"])) {
    $config_ldap->update($_POST);
    Html::back();
} else {
    if (isset($_POST["add"])) {
        //If no name has been given to this configuration, then go back to the page without adding
        if ($_POST["name"] != "") {
            if ($newID = $config_ldap->add($_POST)) {
                if (AuthLdap::testLDAPConnection($newID)) {
                    Session::addMessageAfterRedirect(__('Test successful'));
                } else {
                    Session::addMessageAfterRedirect(__('Test failed'), false, ERROR);
                }
                Html::redirect($CFG_GLPI["root_doc"] . "/front/authldap.php?next=extauth_ldap&id=" . $newID);
            }
        }
        Html::back();
    } else {
        if (isset($_POST["delete"])) {
            $config_ldap->delete($_POST);
            $_SESSION['glpi_authconfig'] = 1;
            $config_ldap->redirectToList();
        } else {
            if (isset($_POST["test_ldap"])) {
                $config_ldap->getFromDB($_POST["id"]);
                if (AuthLdap::testLDAPConnection($_POST["id"])) {
                    //TRANS: %s is the description of the test
Example #24
0
 /**
  * Cron action on reservation : alert on end of reservations
  *
  * @param $task to log, if NULL use display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronReservation($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $items_infos = array();
     $items_messages = array();
     foreach (Entity::getEntitiesToNotify('use_reservations_alert') as $entity => $value) {
         $secs = $value * HOUR_TIMESTAMP;
         // Reservation already begin and reservation ended in $value hours
         $query_end = "SELECT `glpi_reservationitems`.*,\n                              `glpi_reservations`.`end` AS `end`,\n                              `glpi_reservations`.`id` AS `resaid`\n                       FROM `glpi_reservations`\n                       LEFT JOIN `glpi_alerts`\n                           ON (`glpi_reservations`.`id` = `glpi_alerts`.`items_id`\n                               AND `glpi_alerts`.`itemtype` = 'Reservation'\n                               AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                       LEFT JOIN `glpi_reservationitems`\n                           ON (`glpi_reservations`.`reservationitems_id`\n                                 = `glpi_reservationitems`.`id`)\n                       WHERE `glpi_reservationitems`.`entities_id` = '{$entity}'\n                             AND (UNIX_TIMESTAMP(`glpi_reservations`.`end`) - {$secs}) < UNIX_TIMESTAMP()\n                             AND `glpi_reservations`.`begin` < NOW()\n                             AND `glpi_alerts`.`date` IS NULL";
         foreach ($DB->request($query_end) as $data) {
             if ($item_resa = getItemForItemtype($data['itemtype'])) {
                 if ($item_resa->getFromDB($data["items_id"])) {
                     $data['item_name'] = $item_resa->getName();
                     $data['entity'] = $entity;
                     $items_infos[$entity][$data['resaid']] = $data;
                     if (!isset($items_messages[$entity])) {
                         $items_messages[$entity] = __('Device reservations expiring today') . "<br>";
                     }
                     $items_messages[$entity] .= sprintf(__('%1$s - %2$s'), $item_resa->getTypeName(), $item_resa->getName()) . "<br>";
                 }
             }
         }
     }
     foreach ($items_infos as $entity => $items) {
         $resitem = new self();
         if (NotificationEvent::raiseEvent("alert", new Reservation(), array('entities_id' => $entity, 'items' => $items))) {
             $message = $items_messages[$entity];
             $cron_status = 1;
             if ($task) {
                 $task->addVolume(1);
                 $task->log(sprintf(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), $message));
             } else {
                 //TRANS: %1$s is a name, %2$s is text of message
                 Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName("glpi_entities", $entity), $message));
             }
             $alert = new Alert();
             $input["itemtype"] = 'Reservation';
             $input["type"] = Alert::END;
             foreach ($items as $resaid => $item) {
                 $input["items_id"] = $resaid;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
             //TRANS: %s is entity name
             $msg = sprintf(__('%1$s: %2$s'), $entityname, __('Send reservation alert failed'));
             if ($task) {
                 $task->log($msg);
             } else {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             }
         }
     }
     return $cron_status;
 }
Example #25
0
 You should have received a copy of the GNU General Public License
 along with Positions. If not, see <http://www.gnu.org/licenses/>.
 --------------------------------------------------------------------------
*/
include '../../../inc/includes.php';
$img = new PluginPositionsImageItem();
if (isset($_POST["add"]) && isset($_POST['type'])) {
    $test = explode(";", $_POST['type']);
    if (isset($test[0]) && isset($test[1]) && !empty($test[1])) {
        $_POST['type'] = $test[1];
        $_POST['itemtype'] = $test[0];
        if ($img->canCreate()) {
            if (!empty($_POST["img"])) {
                $img->addItemImage($_POST);
            } else {
                Session::addMessageAfterRedirect(__('No picture uploaded', 'positions'), false, ERROR);
            }
        }
    }
    Html::back();
} else {
    if (isset($_POST["delete"])) {
        $img->getFromDB($_POST["id"], -1);
        foreach ($_POST["item"] as $key => $val) {
            if ($val == 1) {
                $img->delete(array('id' => $key));
            }
        }
        Html::back();
    } else {
        Html::header(PluginPositionsPosition::getTypeName(), '', "tools", "pluginpositionsmenu", "config");
Example #26
0
 function pre_updateInDB()
 {
     global $DB;
     if (($key = array_search('name', $this->updates)) !== false) {
         /// Check if user does not exists
         $query = "SELECT *\n                   FROM `" . $this->getTable() . "`\n                   WHERE `name` = '" . $this->input['name'] . "'\n                         AND `id` <> '" . $this->input['id'] . "';";
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             //To display a message
             $this->fields['name'] = $this->oldvalues['name'];
             unset($this->updates[$key]);
             unset($this->oldvalues['name']);
             Session::addMessageAfterRedirect(__('Unable to update login. A user already exists.'), false, ERROR);
         }
     }
     /// Security system except for login update
     if (Session::getLoginUserID() && !Session::haveRight("user", "w") && !strpos($_SERVER['PHP_SELF'], "login.php")) {
         if (Session::getLoginUserID() === $this->input['id']) {
             if (isset($this->fields["authtype"])) {
                 // extauth ldap case
                 if ($_SESSION["glpiextauth"] && ($this->fields["authtype"] == Auth::LDAP || Auth::isAlternateAuth($this->fields["authtype"]))) {
                     $authtype = Auth::getMethodsByID($this->fields["authtype"], $this->fields["auths_id"]);
                     if (count($authtype)) {
                         $fields = AuthLDAP::getSyncFields($authtype);
                         foreach ($fields as $key => $val) {
                             if (!empty($val) && ($key2 = array_search($key, $this->updates)) !== false) {
                                 unset($this->updates[$key2]);
                                 unset($this->oldvalues[$key]);
                             }
                         }
                     }
                 }
                 if (($key = array_search("is_active", $this->updates)) !== false) {
                     unset($this->updates[$key]);
                     unset($this->oldvalues['is_active']);
                 }
                 if (($key = array_search("comment", $this->updates)) !== false) {
                     unset($this->updates[$key]);
                     unset($this->oldvalues['comment']);
                 }
             }
         }
     }
 }
Example #27
0
 /**
  * check right before delete
  *
  * @since version 0.85
  *
  * @return boolean
  **/
 function pre_deleteItem()
 {
     global $DB;
     if ($this->fields['profile'] & DELETE && countElementsInTable("glpi_profilerights", "`name` = 'profile' AND `rights` & " . DELETE)) {
         Session::addMessageAfterRedirect(__("This profile is the last with write rights on profiles"), false, ERROR);
         Session::addMessageAfterRedirect(__("Deletion refused"), false, ERROR);
         return false;
     }
     return true;
 }
 function sendCommand($url, $action, $a_fields, $fields_string = '', $auth = '')
 {
     if ($fields_string == '') {
         foreach ($a_fields as $key => $value) {
             $fields_string .= $key . '=' . $value . '&';
         }
         rtrim($fields_string, '&');
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url . $action);
     curl_setopt($ch, CURLOPT_POST, count($a_fields));
     curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     if ($auth != '') {
         curl_setopt($ch, CURLOPT_USERPWD, $auth);
     }
     $ret = curl_exec($ch);
     $return = true;
     if ($ret === false) {
         Session::addMessageAfterRedirect(__('Shinken restart failed:', 'monitoring') . ' ' . curl_error($ch), false, ERROR);
         $return = false;
     } else {
         if (strstr($ret, 'error')) {
             Session::addMessageAfterRedirect(__('Shinken restart failed:', 'monitoring') . ' ' . $ret, false, ERROR);
             $return = false;
         }
     }
     curl_close($ch);
     return $return;
 }
Example #29
0
 public function saveAnswers($datas)
 {
     $form = new PluginFormcreatorForm();
     $form->getFromDB($datas['formcreator_form']);
     $query = "SELECT q.`id`, q.`fieldtype`, q.`name`\n                FROM glpi_plugin_formcreator_questions q\n                LEFT JOIN glpi_plugin_formcreator_sections s ON s.`id` = q.`plugin_formcreator_sections_id`\n                WHERE s.`plugin_formcreator_forms_id` = {$datas['formcreator_form']}";
     $result = $GLOBALS['DB']->query($query);
     // Update form answers
     if (isset($_POST['save_formanswer'])) {
         $status = $_POST['status'];
         $this->update(array('id' => (int) $datas['id'], 'status' => $status, 'comment' => isset($_POST['comment']) ? $_POST['comment'] : 'NULL'));
         // Update questions answers
         if ($status == 'waiting') {
             while ($question = $GLOBALS['DB']->fetch_array($result)) {
                 if ($question['fieldtype'] != 'file') {
                     $answer = new PluginFormcreatorAnswer();
                     $found = $answer->find('`plugin_formcreator_formanwers_id` = ' . (int) $datas['id'] . '
                                       AND `plugin_formcreator_question_id` = ' . $question['id']);
                     $found = array_shift($found);
                     $data_value = $datas['formcreator_field_' . $question['id']];
                     if (isset($data_value)) {
                         if (is_array($data_value)) {
                             foreach ($data_value as $key => $value) {
                                 $data_value[$key] = $value;
                             }
                             $answer_value = json_encode($data_value);
                         } else {
                             $answer_value = $data_value;
                         }
                     } else {
                         $answer_value = '';
                     }
                     $answer->update(array('id' => $found['id'], 'answer' => $answer_value));
                 } elseif (isset($_FILES['formcreator_field_' . $question['id']]['tmp_name']) && is_file($_FILES['formcreator_field_' . $question['id']]['tmp_name'])) {
                     $doc = new Document();
                     $answer = new PluginFormcreatorAnswer();
                     $found = $answer->find('`plugin_formcreator_formanwers_id` = ' . (int) $datas['id'] . '
                                       AND `plugin_formcreator_question_id` = ' . $question['id']);
                     $found = array_shift($found);
                     $file_datas = array();
                     $file_datas["name"] = $form->fields['name'] . ' - ' . $question['name'];
                     $file_datas["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id'];
                     $file_datas["is_recursive"] = $form->fields['is_recursive'];
                     Document::uploadDocument($file_datas, $_FILES['formcreator_field_' . $question['id']]);
                     if ($docID = $doc->add($file_datas)) {
                         $table = getTableForItemType('Document');
                         $filename = $_FILES['formcreator_field_' . $question['id']]['name'];
                         $query = "UPDATE {$table} SET filename = '" . $filename . "' WHERE id = " . $docID;
                         $GLOBALS['DB']->query($query);
                         $docItem = new Document_Item();
                         $docItemId = $docItem->add(array('documents_id' => $docID, 'itemtype' => __CLASS__, 'items_id' => (int) $datas['id']));
                         $answer->update(array('id' => $found['id'], 'answer' => $docID));
                     }
                 }
             }
         }
         // Create new form answer object
     } else {
         // Does the form need to be validate ?
         if ($form->fields['validation_required']) {
             $status = 'waiting';
         } else {
             $status = 'accepted';
         }
         $id = $this->add(array('entities_id' => isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id'], 'is_recursive' => $form->fields['is_recursive'], 'plugin_formcreator_forms_id' => $datas['formcreator_form'], 'requester_id' => isset($_SESSION['glpiID']) ? $_SESSION['glpiID'] : 0, 'validator_id' => isset($datas['formcreator_validator']) ? $datas['formcreator_validator'] : 0, 'status' => $status, 'request_date' => date('Y-m-d H:i:s')));
         // Save questions answers
         while ($question = $GLOBALS['DB']->fetch_assoc($result)) {
             // If the answer is set, check if it is an array (then implode id).
             if (isset($datas[$question['id']])) {
                 $question_answer = $datas[$question['id']];
                 if (is_array(json_decode($question_answer))) {
                     $question_answer = json_decode($question_answer);
                     foreach ($question_answer as $key => $value) {
                         $question_answer[$key] = $value;
                     }
                     $question_answer = json_encode($question_answer);
                 } else {
                     $question_answer = $question_answer;
                 }
             } else {
                 $question_answer = '';
             }
             $answer = new PluginFormcreatorAnswer();
             $answerID = $answer->add(array('plugin_formcreator_formanwers_id' => $id, 'plugin_formcreator_question_id' => $question['id'], 'answer' => $question_answer));
             // If the question is a file field, save the file as a document
             if ($question['fieldtype'] == 'file' && isset($_FILES['formcreator_field_' . $question['id']]['tmp_name']) && is_file($_FILES['formcreator_field_' . $question['id']]['tmp_name'])) {
                 $doc = new Document();
                 $file_datas = array();
                 $file_datas["name"] = $form->fields['name'] . ' - ' . $question['name'];
                 $file_datas["entities_id"] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id'];
                 $file_datas["is_recursive"] = $form->fields['is_recursive'];
                 Document::uploadDocument($file_datas, $_FILES['formcreator_field_' . $question['id']]);
                 if ($docID = $doc->add($file_datas)) {
                     $table = getTableForItemType('Document');
                     $filename = $_FILES['formcreator_field_' . $question['id']]['name'];
                     $query = "UPDATE {$table} SET filename = '" . $filename . "' WHERE id = " . $docID;
                     $GLOBALS['DB']->query($query);
                     $docItem = new Document_Item();
                     $docItemId = $docItem->add(array('documents_id' => $docID, 'itemtype' => __CLASS__, 'items_id' => $id));
                     $answer->update(array('id' => $answerID, 'answer' => $docID));
                 }
             }
         }
     }
     NotificationEvent::raiseEvent('plugin_formcreator_form_created', $this);
     if ($form->fields['validation_required'] || $status == 'accepted') {
         switch ($status) {
             case 'waiting':
                 // Notify the validator
                 NotificationEvent::raiseEvent('plugin_formcreator_need_validation', $this);
                 break;
             case 'refused':
                 // Notify the requester
                 NotificationEvent::raiseEvent('plugin_formcreator_refused', $this);
                 break;
             case 'accepted':
                 // Notify the requester
                 if (!$this->generateTarget()) {
                     Session::addMessageAfterRedirect(__('Cannot generate targets!', 'formcreator'), true, ERROR);
                     $this->update(array('id' => $this->getID(), 'status' => 'waiting'));
                 }
                 NotificationEvent::raiseEvent('plugin_formcreator_accepted', $this);
                 return false;
                 break;
         }
     }
     Session::addMessageAfterRedirect(__('The form have been successfully saved!', 'formcreator'), true, INFO);
 }
 /**
  * Cron action on softwares : alert on expired licences
  *
  * @param $task to log, if NULL display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronSoftware($task = NULL)
 {
     global $DB, $CFG_GLPI;
     $cron_status = 1;
     if (!$CFG_GLPI['use_mailing']) {
         return 0;
     }
     $message = array();
     $items_notice = array();
     $items_end = array();
     foreach (Entity::getEntitiesToNotify('use_licenses_alert') as $entity => $value) {
         $before = Entity::getUsedConfig('send_licenses_alert_before_delay', $entity);
         // Check licenses
         $query = "SELECT `glpi_softwarelicenses`.*,\n                          `glpi_softwares`.`name` AS softname\n                   FROM `glpi_softwarelicenses`\n                   INNER JOIN `glpi_softwares`\n                        ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                   LEFT JOIN `glpi_alerts`\n                        ON (`glpi_softwarelicenses`.`id` = `glpi_alerts`.`items_id`\n                            AND `glpi_alerts`.`itemtype` = 'SoftwareLicense'\n                            AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                   WHERE `glpi_alerts`.`date` IS NULL\n                         AND `glpi_softwarelicenses`.`expire` IS NOT NULL\n                         AND DATEDIFF(`glpi_softwarelicenses`.`expire`,\n                                      CURDATE()) < '{$before}'\n                         AND `glpi_softwares`.`is_template` = '0'\n                         AND `glpi_softwares`.`is_deleted` = '0'\n                         AND `glpi_softwares`.`entities_id` = '" . $entity . "'";
         $message = "";
         $items = array();
         foreach ($DB->request($query) as $license) {
             $name = $license['softname'] . ' - ' . $license['name'] . ' - ' . $license['serial'];
             //TRANS: %1$s the license name, %2$s is the expiration date
             $message .= sprintf(__('License %1$s expired on %2$s'), Html::convDate($license["expire"]), $name) . "<br>\n";
             $items[$license['id']] = $license;
         }
         if (!empty($items)) {
             $alert = new Alert();
             $options['entities_id'] = $entity;
             $options['licenses'] = $items;
             if (NotificationEvent::raiseEvent('alert', new self(), $options)) {
                 $entityname = Dropdown::getDropdownName("glpi_entities", $entity);
                 if ($task) {
                     //TRANS: %1$s is the entity, %2$s is the message
                     $task->log(sprintf(__('%1$s: %2$s') . "\n", $entityname, $message));
                     $task->addVolume(1);
                 } else {
                     Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), $entityname, $message));
                 }
                 $input["type"] = Alert::END;
                 $input["itemtype"] = 'SoftwareLicense';
                 // add alerts
                 foreach ($items as $ID => $consumable) {
                     $input["items_id"] = $ID;
                     $alert->add($input);
                     unset($alert->fields['id']);
                 }
             } else {
                 $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
                 //TRANS: %s is entity name
                 $msg = sprintf(__('%1$s: %2$s'), $entityname, __('Send licenses alert failed'));
                 if ($task) {
                     $task->log($msg);
                 } else {
                     Session::addMessageAfterRedirect($msg, false, ERROR);
                 }
             }
         }
     }
     return $cron_status;
 }