Example #1
0
 public function duom_anal()
 {
     $page = new AdminPage();
     $panel = new DuomenuAnalizePanel();
     $panel1 = new Lenteles1();
     $panel2 = new Filters();
     $page->addToContainer(1, $panel1->getHtml());
     $page->addToContainer(2, $panel->getHtml());
     $page->addToContainer(2, $panel2->getHtml());
     $page->pagePrint();
 }
Example #2
0
function tpl_list_heading($colname, $format = "<th%s>%s</th>")
{
    global $proj, $page;
    $imgbase = '<img src="%s" alt="%s" />';
    $class = '';
    $html = eL($colname);
    if ($colname == 'comments' || $colname == 'attachments') {
        $html = sprintf($imgbase, $page->get_image(substr($colname, 0, -1)), $html);
    }
    if (Get::val('order') == $colname) {
        $class = ' class="orderby"';
        $sort1 = Get::safe('sort', 'desc') == 'desc' ? 'asc' : 'desc';
        $sort2 = Get::safe('sort2', 'desc');
        $order2 = Get::safe('order2');
        $html .= '&nbsp;&nbsp;' . sprintf($imgbase, $page->get_image(Get::val('sort')), Get::safe('sort'));
    } else {
        $sort1 = 'desc';
        if (in_array($colname, array('project', 'tasktype', 'category', 'openedby', 'assignedto'))) {
            $sort1 = 'asc';
        }
        $sort2 = Get::safe('sort', 'desc');
        $order2 = Get::safe('order');
    }
    $new_order = array('order' => $colname, 'sort' => $sort1, 'order2' => $order2, 'sort2' => $sort2);
    $html = sprintf('<a title="%s" href="%s">%s</a>', eL('sortthiscolumn'), Filters::noXSS(CreateURL('index', $proj->id, null, array_merge($_GET, $new_order))), $html);
    return sprintf($format, $class, $html);
}
 public static function getInstance()
 {
     if (self::$instance == NULL) {
         self::$instance = new self();
     }
     return self::$instance;
 }
 /**
  * @deprecated
  */
 public static function omitFilter($method, $filter)
 {
     $message = '%s is deprecated, please use %::removeMethodFilter()';
     trigger_error(sprintf($message, __METHOD__, __CLASS__), E_USER_DEPRECATED);
     list(, $method) = Filters::target($method);
     return $this->removeMethodFilter($method, $filter);
 }
 public function testOnceHandler()
 {
     $rawTitle = '  Hello world!!!  ';
     $this->filters->once('before_output_title', 'trim');
     $this->filters->filter('before_output_title', $rawTitle);
     $title = $this->filters->filter('before_output_title', $rawTitle);
     self::assertEquals($rawTitle, $title);
 }
Example #6
0
 function beforeCache(&$input, $plugins)
 {
     $input = preg_replace('|[[:space:]]+[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]|', '<a href="\\0">\\0</a>', $input);
     $input = preg_replace('/[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\\.[a-zA-Z]{2,5}/', '<a href="mailto:\\0">\\0</a>', $input);
     if (!in_array('WikiSyntax', $plugins)) {
         $input = '<p>' . nl2br(Filters::noXSS($input)) . '</p>';
     }
 }
Example #7
0
 /**
  * Filter data.
  * @param $data string|int|array|object
  * @return mixed Filtered data
  */
 public function filterData($data)
 {
     $data_type = gettype($data);
     if ($data_type == 'array' || $data_type == 'object') {
         $data = Filters::filterKeyValuePairs($data);
     } elseif ($data_type == 'string') {
         $data = Filters::filterString($data);
     }
     return $data;
 }
 public function testStopPropagation()
 {
     $rawTitle = '  Hello world!!!  ';
     $this->filters->on('before_output_title', 'trim');
     $this->filters->on('before_output_title', function ($value) {
         throw (new StopPropagation())->setValue($value);
     });
     $this->filters->on('before_output_title', [$this, 'customFilterHandler']);
     $title = $this->filters->filter('before_output_title', $rawTitle);
     self::assertEquals('Hello world!!!', $title);
 }
Example #9
0
 /**
  * Returns kills in json format according to the specified parameters
  *
  * @static
  * @param array $parameters
  * @return array
  */
 public static function getKills($parameters = array())
 {
     $ip = IP::get();
     $userAgent = @$_SERVER["HTTP_USER_AGENT"];
     Log::log("API Fetch: " . $_SERVER["REQUEST_URI"] . " (" . $ip . " / " . $userAgent . ")");
     $tables = array();
     $orWhereClauses = array();
     $andWhereClauses = array();
     Filters::buildFilters($tables, $orWhereClauses, $andWhereClauses, $parameters, true);
     $tables = array_unique($tables);
     //if (sizeof($tables) > 1) throw new Exception("Advanced multi-table searching is currently disabled");
     if (sizeof($tables) == 0) {
         $tables[] = "zz_participants p";
     }
     if (sizeof($tables) == 2) {
         $tablePrefix = "k";
     } else {
         $tablePrefix = substr($tables[0], strlen($tables[0]) - 1, 1);
     }
     $query = "select distinct {$tablePrefix}.killID from ";
     $query .= implode(" left join ", array_unique($tables));
     if (sizeof($tables) == 2) {
         $query .= " on (k.killID = p.killID) ";
     }
     if (sizeof($andWhereClauses) || sizeof($orWhereClauses)) {
         $query .= " where ";
         if (sizeof($orWhereClauses) > 0) {
             $andOr = array_key_exists("combined", $parameters) && $parameters["combined"] == true ? " or " : " and ";
             $query .= " ( " . implode($andOr, $orWhereClauses) . " ) ";
             if (sizeof($andWhereClauses)) {
                 $query .= " and ";
             }
         }
         if (sizeof($andWhereClauses)) {
             $query .= implode(" and ", $andWhereClauses);
         }
     }
     if (array_key_exists("limit", $parameters) && $parameters["limit"] < 200) {
         $limit = $parameters["limit"];
         $offset = 0;
     } else {
         $limit = 200;
         // Hardcoded, yes. This number should never change. -- Squizz
         $page = array_key_exists("page", $parameters) ? (int) $parameters["page"] : 1;
         $offset = ($page - 1) * $limit;
     }
     $orderDirection = array_key_exists("orderDirection", $parameters) ? $parameters["orderDirection"] : "desc";
     $query .= " order by {$tablePrefix}.dttm {$orderDirection} limit {$offset}, {$limit}";
     $cacheTime = 3600;
     $kills = Db::query($query, array(), $cacheTime);
     return self::getJSON($kills, $parameters);
 }
Example #10
0
 public static function getUrlImage($str)
 {
     //removendo os acentos
     $str = trim($str);
     $str = Filters::remove_accents($str);
     //trocando espaço em branco por underline
     $str = eregi_replace('( )', '_', $str);
     //tirando outros caracteres invalidos
     $str = eregi_replace('[^a-z0-9\\_]', '', $str);
     //trocando duplo,tripo,quadrupo... espaço (underline) por 1 underline só
     $str = eregi_replace('[\\_]{2,}', '', $str);
     return strtolower($str);
 }
Example #11
0
 /**
  * Gets killmails
  *
  * @param $parameters an array of parameters to fetch mails for
  * @param $allTime gets all mails from the beginning of time or not
  * @return array
  */
 public static function getKills($parameters = array(), $allTime = true)
 {
     $tables = array();
     $orWhereClauses = array();
     $andWhereClauses = array();
     Filters::buildFilters($tables, $orWhereClauses, $andWhereClauses, $parameters, $allTime);
     $tables = array_unique($tables);
     if (sizeof($tables) == 0) {
         $tables[] = "zz_participants p";
     }
     if (sizeof($tables) == 2) {
         $tablePrefix = "k";
     } else {
         $tablePrefix = substr($tables[0], strlen($tables[0]) - 1, 1);
     }
     $query = "select distinct {$tablePrefix}.killID from ";
     $query .= implode(" left join ", array_unique($tables));
     if (sizeof($tables) == 2) {
         $query .= " on (k.killID = p.killID) ";
     }
     if (sizeof($andWhereClauses) || sizeof($orWhereClauses)) {
         $query .= " where ";
         if (sizeof($orWhereClauses) > 0) {
             $andOr = array_key_exists("combined", $parameters) && $parameters["combined"] == true ? " or " : " and ";
             $query .= " ( " . implode($andOr, $orWhereClauses) . " ) ";
             if (sizeof($andWhereClauses)) {
                 $query .= " and ";
             }
         }
         if (sizeof($andWhereClauses)) {
             $query .= implode(" and ", $andWhereClauses);
         }
     }
     $limit = array_key_exists("limit", $parameters) ? (int) $parameters["limit"] : 50;
     $page = array_key_exists("page", $parameters) ? (int) $parameters["page"] : 1;
     $offset = ($page - 1) * $limit;
     $orderBy = array_key_exists("orderBy", $parameters) ? $parameters["orderBy"] : "{$tablePrefix}.dttm";
     $orderDirection = array_key_exists("orderDirection", $parameters) ? $parameters["orderDirection"] : "desc";
     $query .= " order by {$orderBy} {$orderDirection} limit {$offset}, {$limit}";
     $cacheTime = array_key_exists("cacheTime", $parameters) ? (int) $parameters["cacheTime"] : 120;
     $cacheTime = max(120, $cacheTime);
     if (array_key_exists("log", $parameters)) {
         Db::log($query, array());
     }
     $kills = Db::query($query, array(), $cacheTime);
     $merged = self::getKillsDetails($kills);
     return $merged;
 }
Example #12
0
 function imageAttachment($matches)
 {
     global $db, $baseurl, $user;
     // we'll not blindly make images out of all attachments
     $ext = substr($matches[1], -3);
     if (!in_array($ext, array('png', 'jpg', 'gif'))) {
         return $matches[0];
     }
     $att = $db->x->getRow('SELECT * FROM {attachments} WHERE orig_name = ?', null, $matches[1]);
     $task = Flyspray::GetTaskDetails($att['task_id']);
     if ($att && $user->can_view_task($task)) {
         return sprintf('<img src="%s" alt="%s" />', Filters::noXSS($baseurl . '?getfile=' . $att['attachment_id']), Filters::noXSS($att['orig_name']));
     } else {
         return $matches[0];
     }
 }
Example #13
0
 function action_updateproject()
 {
     global $proj, $db, $baseurl;
     if (Post::val('delete_project')) {
         $url = Post::val('move_to') ? CreateURL(array('pm', 'proj' . Post::num('move_to'), 'prefs')) : $baseurl;
         if (Backend::delete_project($proj->id, Post::val('move_to'))) {
             return array(SUBMIT_OK, L('projectdeleted'), $url);
         } else {
             return array(ERROR_INPUT, L('projectnotdeleted'), $url);
         }
     }
     if (!Post::val('project_title')) {
         return array(ERROR_RECOVER, L('emptytitle'));
     }
     $cols = array('project_title', 'theme_style', 'lang_code', 'default_task', 'default_entry', 'intro_message', 'notify_email', 'notify_jabber', 'notify_subject', 'notify_reply', 'feed_description', 'feed_img_url', 'svn_user', 'svn_url', 'svn_password', 'mail_headers');
     $args = array_map('Post_to0', $cols);
     foreach (array('others_view', 'anon_open', 'send_digest', 'anon_view_tasks', 'anon_group', 'comment_closed', 'auto_assign', 'roadmap_field', 'override_user_lang') as $name) {
         $cols[] = $name;
         $args[] = Post::num($name);
     }
     foreach (array('notify_types', 'changelog_reso', 'syntax_plugins') as $name) {
         $cols[] = $name;
         $args[] = implode(' ', (array) Post::val($name));
     }
     // invalidate the cache if necessary
     if (implode(' ', (array) Post::val('syntax_plugins')) != $proj->prefs['syntax_plugins']) {
         $db->execParam('DELETE FROM {cache} WHERE project_id = ?', $proj->id);
     }
     // carefully check the project prefix...
     $prefix = Post::val('project_prefix');
     // already in use?
     $use = $db->x->GetOne('SELECT project_id FROM {projects} WHERE project_prefix = ? AND project_id != ?', null, array($prefix, $proj->id));
     if (Filters::isAlnum($prefix) && $prefix != 'FS' && !$use) {
         $cols[] = 'project_prefix';
         $args[] = $prefix;
     } else {
         return array(ERROR_RECOVER, L('badprefix'));
     }
     $cols[] = 'last_updated';
     $args[] = time();
     $cols[] = 'default_cat_owner';
     $args[] = Flyspray::UserNameToId(Post::val('default_cat_owner'));
     $db->x->autoExecute('{projects}', array_combine($cols, $args), MDB2_AUTOQUERY_UPDATE, sprintf('project_id = %d', $proj->id));
     $db->x->execParam('UPDATE {projects} SET visible_columns = ? WHERE project_id = ?', array(trim(Post::val('visible_columns')), $proj->id));
     return array(SUBMIT_OK, L('projectupdated'));
 }
Example #14
0
 function Project($id)
 {
     global $db, $fs;
     // Get custom fields
     $fields = $db->x->getAll('SELECT f.*, l.list_type
                                        FROM {fields} f
                                   LEFT JOIN {lists} l ON f.list_id = l.list_id
                                       WHERE f.project_id IN (0, ?) ORDER BY field_name', null, array($id));
     foreach ($fields as $field) {
         $f = new Field($field);
         if ($f->id == $fs->prefs['color_field']) {
             $f->values = $this->get_list($f->prefs, $f->id);
         }
         $this->fields['field' . $field['field_id']] = $f;
     }
     $this->columns = array_combine($this->columns, array_map('L', $this->columns));
     foreach ($this->fields as $field) {
         $this->columns['field' . $field->id] = $field->prefs['field_name'];
     }
     if (is_numeric($id) && $id > 0) {
         $this->prefs = $db->x->getRow("SELECT p.*, c.content AS pm_instructions, c.last_updated AS cache_update\n                                 FROM {projects} p\n                            LEFT JOIN {cache} c ON c.topic = p.project_id AND c.type = 'msg'\n                                WHERE p.project_id = ?", null, array($id));
         if (is_array($this->prefs)) {
             $this->id = (int) $this->prefs['project_id'];
             $this->prefs['visible_columns'] = implode(' ', array_intersect(explode(' ', $this->prefs['visible_columns']), array_keys($this->columns)));
             $this->prefs['theme_style'] = Filters::enum($this->prefs['theme_style'], Flyspray::listThemes());
             return;
         }
     }
     $this->id = 0;
     $this->prefs = array();
     $this->prefs['project_title'] = L('allprojects');
     $this->prefs['feed_description'] = L('feedforall');
     $this->prefs['theme_style'] = $fs->prefs['global_theme'];
     $this->prefs['theme_style'] = Filters::enum($this->prefs['theme_style'], Flyspray::listThemes());
     $this->prefs['lang_code'] = $fs->prefs['lang_code'];
     $this->prefs['others_view'] = 1;
     $this->prefs['intro_message'] = '';
     $this->prefs['anon_open'] = $this->prefs['override_user_lang'] = 0;
     $this->prefs['feed_img_url'] = '';
     $this->prefs['default_entry'] = $fs->prefs['default_entry'];
     $this->prefs['notify_reply'] = '';
     $fs->prefs['visible_columns'] = implode(' ', array_intersect(explode(' ', $fs->prefs['visible_columns']), array_keys($this->columns)));
     return;
 }
 public function get_userlist_by_filter()
 {
     if (!empty($this->postData['filter_set'])) {
         $filter_set = \Filters::getInstance();
         $filter_set->setResellerID(array_key_exists('reseller', $this->postData) ? $this->postData['reseller'] : 0);
         $filter_set->initData('users', 'id');
         $curr_filter_set = \Mysql::getInstance()->from('filter_set')->where(array('id' => $this->postData['filter_set']))->get()->first();
         if (!empty($curr_filter_set) && ($unserialize_data = @unserialize($curr_filter_set['filter_set']))) {
             $filter_data = array();
             foreach ($unserialize_data as $row) {
                 $filter_data[$row[0]] = $row;
             }
             $filters_with_cond = array_filter(array_map(function ($row) use($filter_data) {
                 if (array_key_exists($row['text_id'], $filter_data)) {
                     $value = $row['text_id'] == 'status' || $row['text_id'] == 'state' ? (int) ($filter_data[$row['text_id']][2] - 1 > 0) : $filter_data[$row['text_id']][2];
                     return array($row['method'], $filter_data[$row['text_id']][1], $value);
                 }
             }, $filter_set->getFilters()));
             $filter_set->setFilters($filters_with_cond);
             $this->user_list = $filter_set->getData();
         }
     }
     return $this;
 }
Example #16
0
 public static function loginHandle()
 {
     if (check_post('cc_login_uname', 'cc_login_passwd', 'cc_login_login')) {
         // for security, we don't want session fixation :(
         session_regenerate_id();
         $_SESSION['uname'] = $_POST['cc_login_uname'];
         $_SESSION['pword'] = hash('whirlpool', $_POST['cc_login_passwd']);
         $_SESSION['last_ip'] = $_SERVER['REMOTE_ADDR'];
         $_SESSION['last_user_agent'] = $_SERVER['HTTP_USER_AGENT'];
         if (self::checkSession()) {
             //var_dump(TH_PUB_ADMIN);exit();
             if ($_POST['cc_login_remember'] == "yes") {
                 $host = $_SERVER['HTTP_HOST'];
                 if (substr($host, 0, 4) == "www.") {
                     $host = substr($host, 3);
                 }
                 setcookie('ln', self::packCookie(), time() + 60 * 60 * 24 * 30 * 12);
             }
             cc_redirect(TH_PUB_ADMIN, true);
         } else {
             Filters::bind('post_output_login', 'Users::outputError');
         }
     }
 }
Example #17
0
  if(checkbox)
    checkbox.checked = true;
  var hidden = document.getElementById('id_hidden_' + id);
  if(hidden)
    hidden.disabled = false;
  var conf = document.getElementById('id_confirm');
  if(conf)
    conf.disabled = true;
}
</script>
<?php 
// Set current directory to where the language files are
chdir("../lang");
$lang = @$_GET['lang'];
$fail = '';
if (!$lang || !Filters::isAlnum($lang)) {
    $fail .= "Language code not supplied correctly<br/>\n";
}
if (!file_exists('en.php')) {
    $fail .= "The english language file <code>en.php</code> is missing. Make sure this script is run from the same directory as the language files <code>.../flyspray/lang/</code><br/>\n";
}
if ($fail) {
    die($fail . "<b>Usage:</b> <a href='.langedit.php?lang='>.langedit.php?lang=&lt;lang code&gt;</a> where &lt;lang code&gt; should be replaced by your languge, e.g. <b>de</b> for German.");
}
// Read english language file in array $language (assumed to be UTF-8 encoded)
require_once 'en.php';
if (!is_array(@$language)) {
    die("Invalid language file for english");
}
$count = count($language);
// Read the translation file in array $translation (assumed to be UTF-8 encoded)
Example #18
0
<?php

require_once 'app/autoload.php';
if (isset($_SESSION['chat_login']['id_user'])) {
    // Return
    $return = '';
    // Update dos users
    $users = new UsersModel();
    $users->setFields(array('timestamp'));
    $users->setData(array('timestamp' => date('Y-m-d H:i:s')));
    $users->update($_SESSION['chat_login']['id_user']);
    // Lendo as messages
    $users = new UsersModel();
    $users->setCond('id_room = ' . $_SESSION['chat_login']['id_room']);
    $users->setCond('id != ' . $_SESSION['chat_login']['id_user']);
    $users->setCond('active = 1');
    $users->setOrderBy('user asc');
    $load = $users->load_all();
    $json = array();
    foreach ($load as $line) {
        // Retorno
        $user = Filters::convert(htmlentities($line['user']));
        $return .= '<a href="#" id="user_' . $line['id'] . '" rel="' . $line['id'] . '">' . $user . '</a>';
        $json[] = '["' . $line['id'] . '", "' . $user . '"]';
    }
    echo '[' . implode(',', $json) . ']';
} else {
    echo 'error';
}
Example #19
0
 /**
  * Uses service location (i.e. `Libraries::locate()`) to look up a named class of a particular
  * type, and creates an instance of it, and passes an array of parameters to the constructor.
  *
  * If the given class can't be found, an exception is thrown.
  *
  * @param string $type The type of class as defined by `Libraries::$_paths`.
  * @param string $name The un-namespaced name of the class to instantiate.
  * @param array $options An array of constructor parameters to pass to the class.
  * @return object If the class is found, returns an instance of it, otherwise throws an
  *         exception.
  * @throws lithium\core\ClassNotFoundException Throws an exception if the class can't be found.
  * @filter
  */
 public static function instance($type, $name, array $options = array())
 {
     $params = compact('type', 'name', 'options');
     $_paths =& static::$_paths;
     $implementation = function ($self, $params) use(&$_paths) {
         $name = $params['name'];
         $type = $params['type'];
         if (!$name && !$type) {
             $message = "Invalid class lookup: `\$name` and `\$type` are empty.";
             throw new ClassNotFoundException($message);
         }
         if (!is_string($type) && $type !== null && !isset($_paths[$type])) {
             throw new ClassNotFoundException("Invalid class type `{$type}`.");
         }
         if (!($class = $self::locate($type, $name))) {
             throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not found.");
         }
         if (is_object($class)) {
             return $class;
         }
         if (!(is_string($class) && class_exists($class))) {
             throw new ClassNotFoundException("Class `{$name}` of type `{$type}` not defined.");
         }
         return new $class($params['options']);
     };
     if (!isset(static::$_methodFilters[__FUNCTION__])) {
         return $implementation(get_called_class(), $params);
     }
     $class = get_called_class();
     $method = __FUNCTION__;
     $data = array_merge(static::$_methodFilters[__FUNCTION__], array($implementation));
     return Filters::run($class, $params, compact('data', 'class', 'method'));
 }
Example #20
0
    /**
     * Returns an array of tasks (respecting pagination) and an ID list (all tasks)
     * @param array $args
     * @param array $visible
     * @param integer $offset
     * @param integer $comment
     * @param bool $perpage
     * @access public
     * @return array
     * @version 1.0
     */
    public static function get_task_list($args, $visible, $offset = 0, $perpage = 20)
    {
        global $fs, $proj, $db, $user, $conf;
        /* build SQL statement {{{ */
        // Original SQL courtesy of Lance Conry http://www.rhinosw.com/
        $where = $sql_params = array();
        // echo '<pre>' . print_r($visible, true) . '</pre>';
        // echo '<pre>' . print_r($args, true) . '</pre>';
        // PostgreSQL LIKE searches are by default case sensitive,
        // so we use ILIKE instead. For other databases, in our case
        // only MySQL/MariaDB, LIKE is good for our purposes.
        $LIKEOP = 'LIKE';
        if ($db->dblink->dataProvider == 'postgres') {
            $LIKEOP = 'ILIKE';
        }
        $select = '';
        $groupby = 't.task_id, ';
        $cgroupbyarr = array();
        // Joins absolutely needed for user viewing rights
        $from = ' {tasks} t
-- All tasks have a project!
JOIN {projects} p ON t.project_id = p.project_id';
        // Not needed for anonymous users
        if (!$user->isAnon()) {
            $from .= ' -- Global group always exists
JOIN ({groups} gpg
    JOIN {users_in_groups} gpuig ON gpg.group_id = gpuig.group_id AND gpuig.user_id = ?		
) ON gpg.project_id = 0
-- Project group might exist or not.
LEFT JOIN ({groups} pg
    JOIN {users_in_groups} puig ON pg.group_id = puig.group_id AND puig.user_id = ?	
) ON pg.project_id = t.project_id';
            $sql_params[] = $user->id;
            $sql_params[] = $user->id;
        }
        // Keep this always, could also used for showing assigned users for a task.
        // Keeps the overall logic somewhat simpler.
        $from .= ' LEFT JOIN {assigned} ass ON t.task_id = ass.task_id';
        $from .= ' LEFT JOIN {task_tag} tt ON t.task_id = tt.task_id';
        $cfrom = $from;
        // Seems resution name really is needed...
        $select .= 'lr.resolution_name, ';
        $from .= ' LEFT JOIN {list_resolution} lr ON t.resolution_reason = lr.resolution_id ';
        $groupby .= 'lr.resolution_name, ';
        // Otherwise, only join tables which are really necessary to speed up the db-query
        if (array_get($args, 'type') || in_array('tasktype', $visible)) {
            $select .= ' lt.tasktype_name, ';
            $from .= '
LEFT JOIN {list_tasktype} lt ON t.task_type = lt.tasktype_id ';
            $groupby .= ' lt.tasktype_id, ';
        }
        if (array_get($args, 'status') || in_array('status', $visible)) {
            $select .= ' lst.status_name, ';
            $from .= '
LEFT JOIN {list_status} lst ON t.item_status = lst.status_id ';
            $groupby .= ' lst.status_id, ';
        }
        if (array_get($args, 'cat') || in_array('category', $visible)) {
            $select .= ' lc.category_name AS category_name, ';
            $from .= '
LEFT JOIN {list_category} lc ON t.product_category = lc.category_id ';
            $groupby .= 'lc.category_id, ';
        }
        if (in_array('votes', $visible)) {
            $select .= ' (SELECT COUNT(vot.vote_id) FROM {votes} vot WHERE vot.task_id = t.task_id) AS num_votes, ';
        }
        $maxdatesql = ' GREATEST((SELECT max(c.date_added) FROM {comments} c WHERE c.task_id = t.task_id), t.date_opened, t.date_closed, t.last_edited_time) ';
        $search_for_changes = in_array('lastedit', $visible) || array_get($args, 'changedto') || array_get($args, 'changedfrom');
        if ($search_for_changes) {
            $select .= ' GREATEST((SELECT max(c.date_added) FROM {comments} c WHERE c.task_id = t.task_id), t.date_opened, t.date_closed, t.last_edited_time) AS max_date, ';
            $cgroupbyarr[] = 't.task_id';
        }
        if (array_get($args, 'search_in_comments')) {
            $from .= '
LEFT JOIN {comments} c ON t.task_id = c.task_id ';
            $cfrom .= '
LEFT JOIN {comments} c ON t.task_id = c.task_id ';
            $cgroupbyarr[] = 't.task_id';
        }
        if (in_array('comments', $visible)) {
            $select .= ' (SELECT COUNT(cc.comment_id) FROM {comments} cc WHERE cc.task_id = t.task_id) AS num_comments, ';
        }
        if (in_array('reportedin', $visible)) {
            $select .= ' lv.version_name AS product_version_name, ';
            $from .= '
LEFT JOIN {list_version} lv ON t.product_version = lv.version_id ';
            $groupby .= 'lv.version_id, ';
        }
        if (array_get($args, 'opened') || in_array('openedby', $visible)) {
            $select .= ' uo.real_name AS opened_by_name, ';
            $from .= '
LEFT JOIN {users} uo ON t.opened_by = uo.user_id ';
            $groupby .= 'uo.user_id, ';
            if (array_get($args, 'opened')) {
                $cfrom .= '
LEFT JOIN {users} uo ON t.opened_by = uo.user_id ';
            }
        }
        if (array_get($args, 'closed')) {
            $select .= ' uc.real_name AS closed_by_name, ';
            $from .= '
LEFT JOIN {users} uc ON t.closed_by = uc.user_id ';
            $groupby .= 'uc.user_id, ';
            $cfrom .= '
LEFT JOIN {users} uc ON t.closed_by = uc.user_id ';
        }
        if (array_get($args, 'due') || in_array('dueversion', $visible)) {
            $select .= ' lvc.version_name AS closedby_version_name, ';
            $from .= '
LEFT JOIN {list_version} lvc ON t.closedby_version = lvc.version_id ';
            $groupby .= 'lvc.version_id, lvc.list_position, ';
        }
        if (in_array('os', $visible)) {
            $select .= ' los.os_name AS os_name, ';
            $from .= '
LEFT JOIN {list_os} los ON t.operating_system = los.os_id ';
            $groupby .= 'los.os_id, ';
        }
        if (in_array('attachments', $visible)) {
            $select .= ' (SELECT COUNT(attc.attachment_id) FROM {attachments} attc WHERE attc.task_id = t.task_id) AS num_attachments, ';
        }
        if (array_get($args, 'has_attachment')) {
            $where[] = 'EXISTS (SELECT 1 FROM {attachments} att WHERE t.task_id = att.task_id)';
        }
        # 20150213 currently without recursive subtasks!
        if (in_array('effort', $visible)) {
            $select .= ' (SELECT SUM(ef.effort) FROM {effort} ef WHERE t.task_id = ef.task_id) AS effort, ';
        }
        if (array_get($args, 'dev') || in_array('assignedto', $visible)) {
            # not every db system has this feature out of box
            if ('mysql' == $db->dblink->dataProvider) {
                #$select .= ' GROUP_CONCAT(u.real_name) AS assigned_to_name, ';
                # without distinct i see multiple times each assignee
                # maybe performance penalty due distinct?, solve by better groupby construction?
                $select .= ' GROUP_CONCAT(DISTINCT u.real_name) AS assigned_to_name, ';
                # maybe later for building links to users
                #$select .= ' GROUP_CONCAT(DISTINCT u.real_name ORDER BY u.user_id) AS assigned_to_name, ';
                #$select .= ' GROUP_CONCAT(DISTINCT u.user_id ORDER BY u.user_id) AS assignedids, ';
            } else {
                $select .= ' MIN(u.real_name) AS assigned_to_name, ';
                $select .= ' (SELECT COUNT(assc.user_id) FROM {assigned} assc WHERE assc.task_id = t.task_id)  AS num_assigned, ';
            }
            // assigned table is now always included in join
            $from .= '
LEFT JOIN {users} u ON ass.user_id = u.user_id ';
            $groupby .= 'ass.task_id, ';
            if (array_get($args, 'dev')) {
                $cfrom .= '
LEFT JOIN {users} u ON ass.user_id = u.user_id ';
                $cgroupbyarr[] = 't.task_id';
                $cgroupbyarr[] = 'ass.task_id';
            }
        }
        # not every db system has this feature out of box
        if ('mysql' == $db->dblink->dataProvider) {
            # without distinct i see multiple times each tag (when task has several assignees too)
            $select .= ' GROUP_CONCAT(DISTINCT tg.tag_name ORDER BY tg.list_position) AS tags, ';
            $select .= ' GROUP_CONCAT(DISTINCT tg.tag_id ORDER BY tg.list_position) AS tagids, ';
            $select .= ' GROUP_CONCAT(DISTINCT tg.class ORDER BY tg.list_position) AS tagclass, ';
        } else {
            # FIXME: GROUP_CONCAT() for postgresql?
            $select .= ' MIN(tg.tag_name) AS tags, ';
            #$select .= ' (SELECT COUNT(tt.tag_id) FROM {task_tag} tt WHERE tt.task_id = t.task_id)  AS tagnum, ';
            $select .= ' MIN(tg.tag_id) AS tagids, ';
            $select .= " '' AS tagclass, ";
        }
        // task_tag join table is now always included in join
        $from .= '
LEFT JOIN {list_tag} tg ON tt.tag_id = tg.tag_id ';
        $groupby .= 'tt.task_id, ';
        $cfrom .= '
LEFT JOIN {list_tag} tg ON tt.tag_id = tg.tag_id ';
        $cgroupbyarr[] = 't.task_id';
        $cgroupbyarr[] = 'tt.task_id';
        # use preparsed task description cache for dokuwiki when possible
        if ($conf['general']['syntax_plugin'] == 'dokuwiki' && FLYSPRAY_USE_CACHE == true) {
            $select .= ' cache.content desccache, ';
            $from .= '
LEFT JOIN {cache} cache ON t.task_id=cache.topic AND cache.type="task" ';
        } else {
            $select .= 'NULL AS desccache, ';
        }
        if (array_get($args, 'only_primary')) {
            $where[] = 'NOT EXISTS (SELECT 1 FROM {dependencies} dep WHERE dep.dep_task_id = t.task_id)';
        }
        # feature FS#1600
        if (array_get($args, 'only_blocker')) {
            $where[] = 'EXISTS (SELECT 1 FROM {dependencies} dep WHERE dep.dep_task_id = t.task_id)';
        }
        if (array_get($args, 'only_blocked')) {
            $where[] = 'EXISTS (SELECT 1 FROM {dependencies} dep WHERE dep.task_id = t.task_id)';
        }
        # feature FS#1599
        if (array_get($args, 'only_unblocked')) {
            $where[] = 'NOT EXISTS (SELECT 1 FROM {dependencies} dep WHERE dep.task_id = t.task_id)';
        }
        if (array_get($args, 'hide_subtasks')) {
            $where[] = 't.supertask_id = 0';
        }
        if (array_get($args, 'only_watched')) {
            $where[] = 'EXISTS (SELECT 1 FROM {notifications} fsn WHERE t.task_id = fsn.task_id AND fsn.user_id = ?)';
            $sql_params[] = $user->id;
        }
        if ($proj->id) {
            $where[] = 't.project_id = ?';
            $sql_params[] = $proj->id;
        } else {
            if (!$user->isAnon()) {
                // Anon-case handled later.
                $allowed = array();
                foreach ($fs->projects as $p) {
                    $allowed[] = $p['project_id'];
                }
                if (count($allowed) > 0) {
                    $where[] = 't.project_id IN (' . implode(',', $allowed) . ')';
                } else {
                    $where[] = '0 = 1';
                    # always empty result
                }
            }
        }
        // process users viewing rights, if not anonymous
        if (!$user->isAnon()) {
            $where[] = '
(   -- Begin block where users viewing rights are checked.
    -- Case everyone can see all project tasks anyway and task not private
    (t.mark_private = 0 AND p.others_view = 1)
    OR
    -- Case admin or project manager, can see any task, even private
    (gpg.is_admin = 1 OR gpg.manage_project = 1 OR pg.is_admin = 1 OR pg.manage_project = 1)
    OR
    -- Case allowed to see all tasks, but not private
    ((gpg.view_tasks = 1 OR pg.view_tasks = 1) AND t.mark_private = 0)
    OR
    -- Case allowed to see own tasks (automatically covers private tasks also for this user!)
    ((gpg.view_own_tasks = 1 OR pg.view_own_tasks = 1) AND (t.opened_by = ? OR ass.user_id = ?))
    OR
    -- Case task is private, but user either opened it or is an assignee
    (t.mark_private = 1 AND (t.opened_by = ? OR ass.user_id = ?))
    OR
    -- Leave groups tasks as the last one to check. They are the only ones that actually need doing a subquery
    -- for checking viewing rights. There\'s a chance that a previous check already matched and the subquery is
    -- not executed at all. All this of course depending on how the database query optimizer actually chooses
    -- to fetch the results and execute this query... At least it has been given the hint.

    -- Case allowed to see groups tasks, all projects (NOTE: both global and project specific groups accepted here)
    -- Strange... do not use OR here with user_id in EXISTS clause, seems to prevent using index with both mysql and
    -- postgresql, query times go up a lot. So it\'ll be 2 different EXISTS OR\'ed together.
    (gpg.view_groups_tasks = 1 AND t.mark_private = 0 AND (
	EXISTS (SELECT 1 FROM {users_in_groups} WHERE (group_id = pg.group_id OR group_id = gpg.group_id) AND user_id = t.opened_by)
	OR
	EXISTS (SELECT 1 FROM {users_in_groups} WHERE (group_id = pg.group_id OR group_id = gpg.group_id) AND user_id = ass.user_id)
    ))
    OR
    -- Case allowed to see groups tasks, current project. Only project group allowed here.
    (pg.view_groups_tasks = 1 AND t.mark_private = 0 AND (
	EXISTS (SELECT 1 FROM {users_in_groups} WHERE group_id = pg.group_id AND user_id = t.opened_by)
	OR
	EXISTS (SELECT 1 FROM {users_in_groups} WHERE group_id = pg.group_id AND user_id = ass.user_id)
    ))
)   -- Rights have been checked 
';
            $sql_params[] = $user->id;
            $sql_params[] = $user->id;
            $sql_params[] = $user->id;
            $sql_params[] = $user->id;
        }
        /// process search-conditions {{{
        $submits = array('type' => 'task_type', 'sev' => 'task_severity', 'due' => 'closedby_version', 'reported' => 'product_version', 'cat' => 'product_category', 'status' => 'item_status', 'percent' => 'percent_complete', 'pri' => 'task_priority', 'dev' => array('ass.user_id', 'u.user_name', 'u.real_name'), 'opened' => array('opened_by', 'uo.user_name', 'uo.real_name'), 'closed' => array('closed_by', 'uc.user_name', 'uc.real_name'));
        foreach ($submits as $key => $db_key) {
            $type = array_get($args, $key, $key == 'status' ? 'open' : '');
            settype($type, 'array');
            if (in_array('', $type)) {
                continue;
            }
            $temp = '';
            $condition = '';
            foreach ($type as $val) {
                // add conditions for the status selection
                if ($key == 'status' && $val == 'closed' && !in_array('open', $type)) {
                    $temp .= ' is_closed = 1 AND';
                } elseif ($key == 'status' && !in_array('closed', $type)) {
                    $temp .= ' is_closed = 0 AND';
                }
                if (is_numeric($val) && !is_array($db_key) && !($key == 'status' && $val == 'closed')) {
                    $temp .= ' ' . $db_key . ' = ?  OR';
                    $sql_params[] = $val;
                } elseif (is_array($db_key)) {
                    if ($key == 'dev' && ($val == 'notassigned' || $val == '0' || $val == '-1')) {
                        $temp .= ' ass.user_id is NULL OR';
                    } else {
                        foreach ($db_key as $singleDBKey) {
                            if (strpos($singleDBKey, '_name') !== false) {
                                $temp .= ' ' . $singleDBKey . " {$LIKEOP} ? OR";
                                $sql_params[] = '%' . $val . '%';
                            } elseif (is_numeric($val)) {
                                $temp .= ' ' . $singleDBKey . ' = ? OR';
                                $sql_params[] = $val;
                            }
                        }
                    }
                }
                // Add the subcategories to the query
                if ($key == 'cat') {
                    $result = $db->Query('SELECT *
                                            FROM {list_category}
                                           WHERE category_id = ?', array($val));
                    $cat_details = $db->FetchRow($result);
                    $result = $db->Query('SELECT *
                                            FROM {list_category}
                                           WHERE lft > ? AND rgt < ? AND project_id  = ?', array($cat_details['lft'], $cat_details['rgt'], $cat_details['project_id']));
                    while ($row = $db->FetchRow($result)) {
                        $temp .= ' product_category = ?  OR';
                        $sql_params[] = $row['category_id'];
                    }
                }
            }
            if ($temp) {
                $where[] = '(' . substr($temp, 0, -3) . ')';
            }
        }
        /// }}}
        $order_keys = array('id' => 't.task_id', 'project' => 'project_title', 'tasktype' => 'tasktype_name', 'dateopened' => 'date_opened', 'summary' => 'item_summary', 'severity' => 'task_severity', 'category' => 'lc.category_name', 'status' => 'is_closed, item_status', 'dueversion' => 'lvc.list_position', 'duedate' => 'due_date', 'progress' => 'percent_complete', 'lastedit' => 'max_date', 'priority' => 'task_priority', 'openedby' => 'uo.real_name', 'reportedin' => 't.product_version', 'assignedto' => 'u.real_name', 'dateclosed' => 't.date_closed', 'os' => 'los.os_name', 'votes' => 'num_votes', 'attachments' => 'num_attachments', 'comments' => 'num_comments', 'private' => 'mark_private', 'supertask' => 't.supertask_id');
        // make sure that only columns can be sorted that are visible (and task severity, since it is always loaded)
        $order_keys = array_intersect_key($order_keys, array_merge(array_flip($visible), array('severity' => 'task_severity')));
        // Implementing setting "Default order by"
        if (!array_key_exists('order', $args)) {
            # now also for $proj->id=0 (allprojects)
            $orderBy = $proj->prefs['sorting'][0]['field'];
            $sort = $proj->prefs['sorting'][0]['dir'];
            if (count($proj->prefs['sorting']) > 1) {
                $orderBy2 = $proj->prefs['sorting'][1]['field'];
                $sort2 = $proj->prefs['sorting'][1]['dir'];
            } else {
                $orderBy2 = 'severity';
                $sort2 = 'DESC';
            }
        } else {
            $orderBy = $args['order'];
            $sort = $args['sort'];
            $orderBy2 = 'severity';
            $sort2 = 'desc';
        }
        // TODO: Fix this! If something is already ordered by task_id, there's
        // absolutely no use to even try to order by something else also.
        $order_column[0] = $order_keys[Filters::enum(array_get($args, 'order', $orderBy), array_keys($order_keys))];
        $order_column[1] = $order_keys[Filters::enum(array_get($args, 'order2', $orderBy2), array_keys($order_keys))];
        $sortorder = sprintf('%s %s, %s %s, t.task_id ASC', $order_column[0], Filters::enum(array_get($args, 'sort', $sort), array('asc', 'desc')), $order_column[1], Filters::enum(array_get($args, 'sort2', $sort2), array('asc', 'desc')));
        $having = array();
        $dates = array('duedate' => 'due_date', 'changed' => $maxdatesql, 'opened' => 'date_opened', 'closed' => 'date_closed');
        foreach ($dates as $post => $db_key) {
            $var = $post == 'changed' ? 'having' : 'where';
            if ($date = array_get($args, $post . 'from')) {
                ${$var}[] = '(' . $db_key . ' >= ' . Flyspray::strtotime($date) . ')';
            }
            if ($date = array_get($args, $post . 'to')) {
                ${$var}[] = '(' . $db_key . ' <= ' . Flyspray::strtotime($date) . ' AND ' . $db_key . ' > 0)';
            }
        }
        if (array_get($args, 'string')) {
            $words = explode(' ', strtr(array_get($args, 'string'), '()', '  '));
            $comments = '';
            $where_temp = array();
            if (array_get($args, 'search_in_comments')) {
                $comments .= " OR c.comment_text {$LIKEOP} ?";
            }
            if (array_get($args, 'search_in_details')) {
                $comments .= " OR t.detailed_desc {$LIKEOP} ?";
            }
            foreach ($words as $word) {
                $likeWord = '%' . str_replace('+', ' ', trim($word)) . '%';
                $where_temp[] = "(t.item_summary {$LIKEOP} ? OR t.task_id = ? {$comments})";
                array_push($sql_params, $likeWord, intval($word));
                if (array_get($args, 'search_in_comments')) {
                    array_push($sql_params, $likeWord);
                }
                if (array_get($args, 'search_in_details')) {
                    array_push($sql_params, $likeWord);
                }
            }
            $where[] = '(' . implode(array_get($args, 'search_for_all') ? ' AND ' : ' OR ', $where_temp) . ')';
        }
        if ($user->isAnon()) {
            $where[] = 't.mark_private = 0 AND p.others_view = 1';
            if (array_key_exists('status', $args)) {
                if (in_array('closed', $args['status']) && !in_array('open', $args['status'])) {
                    $where[] = 't.is_closed = 1';
                } elseif (in_array('open', $args['status']) && !in_array('closed', $args['status'])) {
                    $where[] = 't.is_closed = 0';
                }
            }
        }
        $where = count($where) ? 'WHERE ' . join(' AND ', $where) : '';
        // Get the column names of table tasks for the group by statement
        if (!strcasecmp($conf['database']['dbtype'], 'pgsql')) {
            $groupby .= "p.project_title, p.project_is_active, ";
            // Remove this after checking old PostgreSQL docs.
            // 1 column from task table should be enough, after
            // already grouping by task_id, there's no possibility
            // to have anything more in that table to group by.
            $groupby .= $db->GetColumnNames('{tasks}', 't.task_id', 't.');
        } else {
            $groupby = 't.task_id';
        }
        $having = count($having) ? 'HAVING ' . join(' AND ', $having) : '';
        // echo '<pre>' . print_r($args, true) . '</pre>';
        // echo '<pre>' . print_r($cgroupbyarr, true) . '</pre>';
        $cgroupby = count($cgroupbyarr) ? 'GROUP BY ' . implode(',', array_unique($cgroupbyarr)) : '';
        $sqlcount = "SELECT  COUNT(*) FROM (SELECT 1, t.task_id, t.date_opened, t.date_closed, t.last_edited_time\n                           FROM     {$cfrom}\n                           {$where}\n                           {$cgroupby}\n                           {$having}) s";
        $sqltext = "SELECT t.*, {$select}\np.project_title, p.project_is_active\nFROM {$from}\n{$where}\nGROUP BY {$groupby}\n{$having}\nORDER BY {$sortorder}";
        // Very effective alternative with a little bit more work
        // and if row_number() can be emulated in mysql. Idea:
        // Move every join and other operation not needed in
        // the inner clause to select rows to the outer query,
        // and do the rest when we already know which rows
        // are in the window to show. Got it to run constantly
        // under 6000 ms.
        /* Leave this for next version, don't have enough time for testing.
                $sqlexperiment = "SELECT * FROM (
        SELECT row_number() OVER(ORDER BY task_id) AS rownum,
        t.*, $select p.project_title, p.project_is_active FROM $from
        $where
        GROUP BY $groupby
        $having
        ORDER BY $sortorder
        )
        t WHERE rownum BETWEEN $offset AND " . ($offset + $perpage);
        */
        // echo '<pre>'.print_r($sql_params, true).'</pre>'; # for debugging
        // echo '<pre>'.$sqlcount.'</pre>'; # for debugging
        // echo '<pre>'.$sqltext.'</pre>'; # for debugging
        $sql = $db->Query($sqlcount, $sql_params);
        $totalcount = $db->FetchOne($sql);
        # 20150313 peterdd: Do not override task_type with tasktype_name until we changed t.task_type to t.task_type_id! We need the id too.
        $sql = $db->Query($sqltext, $sql_params, $perpage, $offset);
        // $sql = $db->Query($sqlexperiment, $sql_params);
        $tasks = $db->fetchAllArray($sql);
        $id_list = array();
        $limit = array_get($args, 'limit', -1);
        $forbidden_tasks_count = 0;
        foreach ($tasks as $key => $task) {
            $id_list[] = $task['task_id'];
            if (!$user->can_view_task($task)) {
                unset($tasks[$key]);
                $forbidden_tasks_count++;
            }
        }
        // Work on this is not finished until $forbidden_tasks_count is always zero.
        // echo "<pre>$offset : $perpage : $totalcount : $forbidden_tasks_count</pre>";
        return array($tasks, $id_list, $totalcount, $forbidden_tasks_count);
        // # end alternative
    }
Example #21
0
<?php

require 'app/inc/autoload.php';
if (isset($_POST) && !empty($_POST)) {
    $user = Filters::anti_sql_injection($_POST['user']);
    $password = md5($_POST['password']);
    $admin_model = new AdminModel();
    $admin_model->setCond('user = "******"');
    $admin_model->setCond('password = "******"');
    $load = $admin_model->load();
    if (!empty($load)) {
        $_SESSION['id_admin'] = $load[0]['id'];
        $_SESSION['user_admin'] = $load[0]['user'];
        $_SESSION['password_admin'] = $load[0]['password'];
    }
}
// Check login
if (isset($_SESSION['user_admin']) && isset($_SESSION['password_admin'])) {
    header('location: index.php');
    exit;
}
Template::getHeader();
?>
	<div id="content">
		<form method="post" name="login" action="login.php">
			<div class="block_field">
				<label for="user">User<label>
				<input type="text" name="user" id="user" size="30" />
			</div>
			<div class="block_field">
				<label for="password">Password<label>
Example #22
0
 /**
  * Returns an array of tasks (respecting pagination) and an ID list (all tasks)
  * @param array $args call by reference because we have to modifiy $_GET if we use default values from a user profile
  * @param array $visible
  * @param integer $offset
  * @param integer $comment
  * @param bool $perpage
  * @access public
  * @return array
  * @version 1.0
  */
 function get_task_list(&$args, $visible, $offset = 0, $perpage = null)
 {
     global $proj, $db, $user, $conf, $fs;
     /* build SQL statement {{{ */
     // Original SQL courtesy of Lance Conry http://www.rhinosw.com/
     $where = $sql_params = array();
     $select = '';
     $groupby = 't.task_id, ';
     $from = '             {tasks}         t
                  LEFT JOIN  {projects}      p   ON t.project_id = p.project_id
                  LEFT JOIN  {list_items} lr ON t.resolution_reason = lr.list_item_id
                  LEFT JOIN  {redundant} r ON t.task_id = r.task_id ';
     // Only join tables which are really necessary to speed up the db-query
     $from .= ' LEFT JOIN  {assigned} ass      ON t.task_id = ass.task_id ';
     $from .= ' LEFT JOIN  {users} u           ON ass.user_id = u.user_id ';
     if (array_get($args, 'dev') || in_array('assignedto', $visible)) {
         $select .= ' MIN(u.real_name)               AS assigned_to_name, ';
         $select .= ' COUNT(ass.user_id)    AS num_assigned, ';
     }
     if (array_get($args, 'only_primary')) {
         $from .= ' LEFT JOIN  {dependencies} dep  ON dep.dep_task_id = t.task_id ';
         $where[] = 'dep.depend_id IS null';
     }
     if (array_get($args, 'has_attachment')) {
         $where[] = 'attachment_count > 0';
     }
     // sortable default fields
     $order_keys = array('id' => 't.task_id %s', 'project' => 'project_title %s', 'dateopened' => 'date_opened %s', 'summary' => 'item_summary %s', 'progress' => 'percent_complete %s', 'lastedit' => 'last_changed_time %s', 'openedby' => 'r.opened_by_real_name %s', 'closedby' => 'r.closed_by_real_name %s', 'changedby' => 'r.last_changed_by_real_name %s', 'assignedto' => 'u.real_name %s', 'dateclosed' => 't.date_closed %s', 'votes' => 'vote_count %s', 'attachments' => 'attachment_count %s', 'comments' => 'comment_count %s', 'state' => 'closed_by %1$s, is_closed %1$s', 'projectlevelid' => 'prefix_id %s', 'private' => 'mark_private %s');
     // custom sortable fields
     foreach ($proj->fields as $field) {
         if ($field->prefs['list_type'] == LIST_CATEGORY) {
             // consider hierarchical structure of categories
             $order_keys['field' . $field->id] = 'lcfield' . $field->id . '.lft %1$s, field' . $field->id . ' %1$s';
         } else {
             $order_keys['field' . $field->id] = 'field' . $field->id . ' %s';
         }
     }
     // Default user sort column and order
     if (!$user->isAnon()) {
         if (!isset($args['sort'])) {
             $args['sort'] = $user->infos['defaultorder'];
         }
         if (!isset($args['order'])) {
             $usercolumns = explode(' ', $user->infos['defaultsortcolumn']);
             foreach ($usercolumns as $column) {
                 if (isset($order_keys[$column])) {
                     $args['order'] = $column;
                     break;
                 }
             }
         }
     }
     // make sure that only columns can be sorted that are visible
     $order_keys = array_intersect_key($order_keys, array_flip($visible));
     $order_column[0] = $order_keys[Filters::enum(array_get($args, 'order', 'id'), array_keys($order_keys))];
     $order_column[1] = $order_keys[Filters::enum(array_get($args, 'order2', 'project'), array_keys($order_keys))];
     $order_column[0] = sprintf($order_column[0], strtoupper(Filters::enum(array_get($args, 'sort', 'desc'), array('asc', 'desc'))));
     $order_column[1] = sprintf($order_column[1], strtoupper(Filters::enum(array_get($args, 'sort2', 'desc'), array('asc', 'desc'))));
     $sortorder = sprintf('%s, %s, t.task_id ASC', $order_column[0], $order_column[1]);
     // search custom fields
     $custom_fields_joined = array();
     foreach ($proj->fields as $field) {
         $ref = 'field' . $field->id;
         if ($field->prefs['field_type'] == FIELD_DATE) {
             if (!array_get($args, 'field' . $field->id . 'from') && !array_get($args, 'field' . $field->id . 'to')) {
                 continue;
             }
             $from .= " LEFT JOIN {field_values} {$ref} ON t.task_id = {$ref}.task_id AND {$ref}.field_id = {$field->id} ";
             $custom_fields_joined[] = $field->id;
             if ($date = array_get($args, 'field' . $field->id . 'from')) {
                 $where[] = "({$ref}.field_value >= ?)";
                 $sql_params[] = Flyspray::strtotime($date);
             }
             if ($date = array_get($args, 'field' . $field->id . 'to')) {
                 $where[] = "({$ref}.field_value <= ? AND {$ref}.field_value > 0)";
                 $sql_params[] = Flyspray::strtotime($date);
             }
         } elseif ($field->prefs['field_type'] == FIELD_LIST) {
             if (in_array('', (array) array_get($args, 'field' . $field->id, array('')))) {
                 continue;
             }
             $from .= " LEFT JOIN {field_values} {$ref} ON t.task_id = {$ref}.task_id AND {$ref}.field_id = {$field->id} ";
             $custom_fields_joined[] = $field->id;
             $fwhere = array();
             foreach ($args['field' . $field->id] as $val) {
                 $fwhere[] = " {$ref}.field_value = ? ";
                 $sql_params[] = $val;
             }
             if (count($fwhere)) {
                 $where[] = ' (' . implode(' OR ', $fwhere) . ') ';
             }
         } else {
             if (!($val = array_get($args, 'field' . $field->id))) {
                 continue;
             }
             $from .= " LEFT JOIN {field_values} {$ref} ON t.task_id = {$ref}.task_id AND {$ref}.field_id = {$field->id} ";
             $custom_fields_joined[] = $field->id;
             $where[] = "({$ref}.field_value LIKE ?)";
             // try to determine a valid user ID if necessary
             if ($field->prefs['field_type'] == FIELD_USER) {
                 $val = Flyspray::UserNameOrId($val);
             }
             $sql_params[] = $val;
         }
     }
     // now join custom fields used in columns
     foreach ($proj->columns as $col => $name) {
         if (preg_match('/^field(\\d+)$/', $col, $match) && (in_array($col, $visible) || $match[1] == $fs->prefs['color_field'])) {
             if (!in_array($match[1], $custom_fields_joined)) {
                 $from .= " LEFT JOIN {field_values} {$col} ON t.task_id = {$col}.task_id AND {$col}.field_id = " . intval($match[1]);
             }
             $from .= " LEFT JOIN {fields} f{$col} ON f{$col}.field_id = {$col}.field_id ";
             // join special tables for certain fields
             if ($proj->fields['field' . $match[1]]->prefs['field_type'] == FIELD_LIST) {
                 $from .= "LEFT JOIN {list_items} li{$col} ON (f{$col}.list_id = li{$col}.list_id AND {$col}.field_value = li{$col}.list_item_id)\n                              LEFT JOIN {list_category} lc{$col} ON (f{$col}.list_id = lc{$col}.list_id AND {$col}.field_value = lc{$col}.category_id) ";
                 if ($proj->fields['field' . $match[1]]->prefs['list_type'] != LIST_CATEGORY) {
                     $select .= " li{$col}.item_name AS {$col}_name, ";
                 } else {
                     $select .= " lc{$col}.category_name AS {$col}_name, ";
                 }
             } else {
                 if ($proj->fields['field' . $match[1]]->prefs['field_type'] == FIELD_USER) {
                     $from .= " LEFT JOIN {users} u{$col} ON {$col}.field_value = u{$col}.user_id ";
                     $select .= " u{$col}.user_name AS {$col}_name, ";
                 }
             }
             $select .= "{$col}.field_value AS {$col}, ";
             // adding data to queries not nice, but otherwise sql_params and joins are not in sync
         }
     }
     // open / closed (never thought that I'd use XOR some time)
     if (in_array('open', array_get($args, 'status', array('open'))) xor in_array('closed', array_get($args, 'status', array()))) {
         $where[] = ' is_closed = ? ';
         $sql_params[] = (int) in_array('closed', array_get($args, 'status', array()));
     }
     /// process search-conditions {{{
     $submits = array('percent' => 'percent_complete', 'dev' => array('a.user_id', 'us.user_name'), 'opened' => array('opened_by', 'r.opened_by_user_name'), 'closed' => array('closed_by', 'r.closed_by_user_name'));
     // add custom user fields
     foreach ($submits as $key => $db_key) {
         $type = array_get($args, $key, '');
         settype($type, 'array');
         if (in_array('', $type)) {
             continue;
         }
         if ($key == 'dev') {
             $from .= 'LEFT JOIN {assigned} a  ON t.task_id = a.task_id ';
             $from .= 'LEFT JOIN {users} us  ON a.user_id = us.user_id ';
         }
         $temp = '';
         $condition = '';
         foreach ($type as $val) {
             if (is_numeric($val) && !is_array($db_key)) {
                 $temp .= ' ' . $db_key . ' = ?  OR';
                 $sql_params[] = $val;
             } elseif (is_array($db_key)) {
                 if ($key == 'dev' && ($val == 'notassigned' || $val == '0' || $val == '-1')) {
                     $temp .= ' a.user_id IS NULL  OR';
                 } else {
                     if (is_numeric($val)) {
                         $condition = ' = ? OR';
                     } else {
                         $val = '%' . $val . '%';
                         $condition = ' LIKE ? OR';
                     }
                     foreach ($db_key as $value) {
                         $temp .= ' ' . $value . $condition;
                         $sql_params[] = $val;
                     }
                 }
             }
         }
         if ($temp) {
             $where[] = '(' . substr($temp, 0, -3) . ')';
         }
     }
     /// }}}
     $having = array();
     $dates = array('due_date', 'changed' => 'r.last_changed_time', 'opened' => 'date_opened', 'closed' => 'date_closed');
     foreach ($dates as $post => $db_key) {
         $var = $post == 'changed' ? 'having' : 'where';
         if ($date = array_get($args, $post . 'from')) {
             ${$var}[] = '(' . $db_key . ' >= ' . Flyspray::strtotime($date) . ')';
         }
         if ($date = array_get($args, $post . 'to')) {
             ${$var}[] = '(' . $db_key . ' <= ' . Flyspray::strtotime($date) . ' AND ' . $db_key . ' > 0)';
         }
     }
     if (array_get($args, 'string')) {
         $words = explode(' ', strtr(array_get($args, 'string'), '()', '  '));
         $comments = '';
         $where_temp = array();
         if (array_get($args, 'search_in_comments')) {
             $from .= 'LEFT JOIN {comments} c  ON t.task_id = c.task_id ';
             $comments .= ' OR c.comment_text LIKE ? ';
         }
         if (array_get($args, 'search_in_details')) {
             $comments .= 'OR t.detailed_desc LIKE ? ';
         }
         foreach ($words as $word) {
             $word = '%' . str_replace('+', ' ', trim($word)) . '%';
             $where_temp[] = "(t.item_summary LIKE ? OR t.task_id LIKE ? {$comments})";
             array_push($sql_params, $word, $word);
             if (array_get($args, 'search_in_comments')) {
                 array_push($sql_params, $word);
             }
             if (array_get($args, 'search_in_details')) {
                 array_push($sql_params, $word);
             }
         }
         $where[] = '(' . implode(array_get($args, 'search_for_all') ? ' AND ' : ' OR ', $where_temp) . ')';
     }
     if (array_get($args, 'only_watched')) {
         //join the notification table to get watched tasks
         $from .= ' LEFT JOIN {notifications} fsn ON t.task_id = fsn.task_id';
         $where[] = 'fsn.user_id = ?';
         $sql_params[] = $user->id;
     }
     if ($proj->id) {
         $where[] = 't.project_id = ?';
         $sql_params[] = $proj->id;
     } else {
         $tmpwhere = array();
         foreach (array_get($args, 'search_project', array()) as $id) {
             if ($id) {
                 $tmpwhere[] = 't.project_id = ?';
                 $sql_params[] = $id;
             }
         }
         if (count($tmpwhere)) {
             $where[] = '(' . implode(' OR ', $tmpwhere) . ')';
         }
     }
     $where = count($where) ? 'WHERE ' . join(' AND ', $where) : '';
     // Get the column names of table tasks for the group by statement
     if (!strcasecmp($conf['database']['dbtype'], 'pgsql')) {
         $order_column[0] = substr($order_column[0], 0, -4);
         $order_column[1] = substr($order_column[1], 0, -4);
         $groupby .= "p.project_title, p.project_prefix, {$order_column[0]},{$order_column[1]}, lr.item_name, ";
         $groupby .= GetColumnNames('{tasks}', 't.task_id', 't');
     } else {
         $groupby = 't.task_id';
     }
     $having = count($having) ? 'HAVING ' . join(' AND ', $having) : '';
     $tasks = $db->x->getAll("\n                          SELECT   t.*, r.*, {$select}\n                                   p.project_title, p.project_prefix,\n                                   lr.item_name AS resolution_name\n                          FROM     {$from}\n                          {$where}\n                          GROUP BY {$groupby}\n                          {$having}\n                          ORDER BY {$sortorder}", null, $sql_params);
     $id_list = array();
     $limit = array_get($args, 'limit', -1);
     $task_count = 0;
     foreach ($tasks as $key => $task) {
         $id_list[] = $task['task_id'];
         if (!$user->can_view_task($task)) {
             unset($tasks[$key]);
             array_pop($id_list);
             --$task_count;
         } elseif ($perpage && ($task_count < $offset || $task_count > $offset - 1 + $perpage || $limit > 0 && $task_count >= $limit)) {
             unset($tasks[$key]);
         }
         ++$task_count;
     }
     return array($tasks, $id_list);
 }
Example #23
0
 /**
  * Filter and return $_GET.
  * @return object
  */
 private function getQueryParameters()
 {
     return Filters::filterKeyValuePairs($_GET);
 }
Example #24
0
function pagenums($pagenum, $perpage, $totalcount)
{
    global $proj;
    $pagenum = intval($pagenum);
    $perpage = intval($perpage);
    $totalcount = intval($totalcount);
    // Just in case $perpage is something weird, like 0, fix it here:
    if ($perpage < 1) {
        $perpage = $totalcount > 0 ? $totalcount : 1;
    }
    $pages = ceil($totalcount / $perpage);
    $output = sprintf(eL('page'), $pagenum, $pages);
    if ($totalcount / $perpage > 1) {
        $params = $_GET;
        # unset unneeded params for shorter urls
        unset($params['do']);
        unset($params['project']);
        unset($params['switch']);
        $output .= '<span class="pagenums DoNotPrint">';
        $start = max(1, $pagenum - 4 + min(2, $pages - $pagenum));
        $finish = min($start + 4, $pages);
        if ($start > 1) {
            $url = Filters::noXSS(CreateURL('tasklist', $proj->id, null, array_merge($params, array('pagenum' => 1))));
            $output .= sprintf('<a href="%s">&lt;&lt;%s </a>', $url, eL('first'));
        }
        if ($pagenum > 1) {
            $url = Filters::noXSS(CreateURL('tasklist', $proj->id, null, array_merge($params, array('pagenum' => $pagenum - 1))));
            $output .= sprintf('<a id="previous" accesskey="p" href="%s">&lt; %s</a> - ', $url, eL('previous'));
        }
        for ($pagelink = $start; $pagelink <= $finish; $pagelink++) {
            if ($pagelink != $start) {
                $output .= ' - ';
            }
            if ($pagelink == $pagenum) {
                $output .= sprintf('<strong>%d</strong>', $pagelink);
            } else {
                $url = Filters::noXSS(CreateURL('tasklist', $proj->id, null, array_merge($params, array('pagenum' => $pagelink))));
                $output .= sprintf('<a href="%s">%d</a>', $url, $pagelink);
            }
        }
        if ($pagenum < $pages) {
            $url = Filters::noXSS(CreateURL('tasklist', $proj->id, null, array_merge($params, array('pagenum' => $pagenum + 1))));
            $output .= sprintf(' - <a id="next" accesskey="n" href="%s">%s &gt;</a>', $url, eL('next'));
        }
        if ($finish < $pages) {
            $url = Filters::noXSS(CreateURL('tasklist', $proj->id, null, array_merge($params, array('pagenum' => $pages))));
            $output .= sprintf('<a href="%s"> %s &gt;&gt;</a>', $url, eL('last'));
        }
        $output .= '</span>';
    }
    return $output;
}
Example #25
0
function tpl_draw_cell($task, $colname, $format = "<td class='%s %s'>%s</td>")
{
    global $fs, $proj, $page;
    $indexes = array('id' => 'task_id', 'project' => 'project_title', 'summary' => 'item_summary', 'dateopened' => 'date_opened', 'openedby' => 'opened_by_real_name', 'closedby' => 'closed_by_real_name', 'changedby' => 'last_changed_by_real_name', 'assignedto' => 'assigned_to_name', 'lastedit' => 'last_changed_time', 'comments' => 'comment_count', 'votes' => 'vote_count', 'attachments' => 'attachment_count', 'dateclosed' => 'date_closed', 'projectlevelid' => 'prefix_id', 'progress' => '', 'state' => '', 'private' => 'mark_private');
    //must be an array , must contain elements and be alphanumeric (permitted  "_")
    if (!is_array($task) || empty($task) || preg_match('![^A-Za-z0-9_]!', $colname)) {
        //run away..
        return '';
    }
    switch ($colname) {
        case 'id':
            $value = tpl_tasklink($task, $task['task_id']);
            break;
        case 'projectlevelid':
            $value = tpl_tasklink($task, $task['project_prefix'] . '#' . $task['prefix_id']);
            break;
        case 'summary':
            $value = tpl_tasklink($task, utf8_substr($task['item_summary'], 0, 55), false, array(), array('state', 'age', 'percent_complete'));
            if (utf8_strlen($task['item_summary']) > 55) {
                $value .= '...';
            }
            break;
        case 'lastedit':
        case 'dateopened':
        case 'dateclosed':
            $value = formatDate($task[$indexes[$colname]]);
            break;
        case 'progress':
            $value = '<div class="taskpercent"><div style="width:' . $task['percent_complete'] . '%"> </div></div>';
            break;
        case 'assignedto':
            $value = Filters::noXSS($task[$indexes[$colname]]);
            if ($task['num_assigned'] > 1) {
                $value .= ', +' . ($task['num_assigned'] - 1);
            }
            break;
        case 'state':
            if ($task['is_closed']) {
                $value = L('closed');
            } elseif ($task['closed_by']) {
                $value = L('reopened');
            } else {
                $value = L('open');
            }
            break;
        case 'private':
            $value = $task[$indexes[$colname]] ? L('yes') : L('no');
            break;
        default:
            if (isset($indexes[$colname])) {
                $value = $task[$indexes[$colname]];
            } elseif (isset($task[$colname . '_name'])) {
                $value = $task[$colname . '_name'];
            } else {
                if (isset($proj->fields[$colname])) {
                    $value = $proj->fields[$colname]->view($task, array(), true);
                } else {
                    $value = $task[$colname];
                }
            }
            $value = Filters::noXSS($value);
            break;
    }
    $wsvalue = str_replace(' ', '', $value);
    return sprintf($format, 'task_' . $colname, Filters::isAlnum($wsvalue) ? $colname . '_' . $wsvalue : '', $value);
}
Example #26
0
 /**
  * Get data para insercao
  */
 public function getData()
 {
     // Deletando fields vazios
     if (count($this->remove_empty)) {
         foreach ($this->remove_empty as $field) {
             if (array_key_exists($field, $this->data) && $this->data[$field] == '') {
                 $key = array_search($field, $this->fields);
                 unset($this->fields[$key]);
             }
         }
     }
     // Aplicando formatação aos valores
     $values = array();
     foreach ($this->fields as $field) {
         if (array_key_exists($field, $this->data)) {
             $treated_value = Filters::anti_sql_injection($this->data[$field]);
             $treated_value = $this->strip_tags ? Filters::strip_tags($treated_value) : $treated_value;
             if (array_key_exists($field, $this->_filters)) {
                 $filter = $this->_filters[$field];
                 $all_filters = get_class_methods('Filters');
                 if (function_exists($filter)) {
                     $treated_value = $filter($treated_value);
                 } else {
                     if (in_array($filter, get_class_methods($this))) {
                         $treated_value = $this->{$filter}($treated_value);
                     } else {
                         if (in_array($filter, $all_filters)) {
                             $treated_value = Filters::$filter($treated_value);
                         }
                     }
                 }
             }
             $values[$field] = '"' . $treated_value . '"';
         } else {
             $values[$field] = '""';
         }
     }
     return $values;
 }
Example #27
0
     $return .= '<div class="' . $class_box . '">';
     $return .= '<span class="head_msg">';
     $return .= '<span class="time_msg">' . date('H:i:s', strtotime($line['timestamp'])) . '</span> ';
     $return .= '<span class="user_name" rel="' . $id_user . '">' . $user_name . '</span> ';
     $return .= '</span> ';
     $return .= '<span class="message_user_' . $line['type'] . '">' . $message . '</span>';
     $return .= '</div>';
 } else {
     // Whose behalf he is receiving
     $name_to = Locale::setContent('All users');
     $users = new UsersModel();
     $users->setCond('active = 1');
     $users->setCond('id = ' . $line['to_user']);
     $user = $users->load_all();
     if (isset($user[0]) && count($user[0])) {
         $name_to = Filters::convert(htmlentities($user[0]['user']));
     }
     $class_box .= $line['reserved'] ? ' box_msg_reserved inline_green' : '';
     $class_box .= $line['to_user'] == $_SESSION['chat_login']['id_user'] ? ' to_you_message' : '';
     $class_box .= $line['id_user'] == $_SESSION['chat_login']['id_user'] ? ' for_you_message' : '';
     if (MESSAGE_TYPE == 'inline') {
         $class_box .= ' box_msg_inline';
     }
     $return .= '<div class="' . $class_box . '">';
     $return .= '<span class="head_msg">';
     $return .= '<span class="time_msg">' . date('H:i:s', strtotime($line['timestamp'])) . '</span> ';
     $return .= '<span class="user_name" rel="' . $id_user . '">' . $user_name . '</span> ';
     $return .= ($line['reserved'] ? '<b>(' . Locale::setContent('reservedly') . ')</b> ' : '') . ' ' . Locale::setContent('tells') . ' ';
     $return .= '<span class="name_to" rel="' . $to_user . '">' . $name_to . '</span>: ';
     $return .= '<span class="remove_message">' . Locale::setContent('Hide message') . '</span> ';
     $return .= '</span>';
Example #28
0
 /**
  * Collects a set of filters to iterate. Creates a filter chain for the given class/method,
  * executes it, and returns the value.
  *
  * @param mixed $class The class for which this filter chain is being created. If this is the
  *        result of a static method call, `$class` should be a string. Otherwise, it should
  *        be the instance of the object making the call.
  * @param array $params An associative array of the given method's parameters.
  * @param array $options The configuration options with which to create the filter chain.
  *        Mainly, these options allow the `Filters` object to be queried for details such as
  *        which class / method initiated it. Available keys:
  *        - `'class'`: The name of the class that initiated the filter chain.
  *        - `'method'`: The name of the method that initiated the filter chain.
  *        - `'data'` _array_: An array of callable objects (usually closures) to be iterated
  *          through. By default, execution will be nested such that the first item will be
  *          executed first, and will be the last to return.
  * @return Returns the value returned by the first closure in `$options['data`]`.
  */
 public static function run($class, $params, array $options = array())
 {
     $defaults = array('class' => null, 'method' => null, 'data' => array());
     $options += $defaults;
     $lazyFilterCheck = is_string($class) && $options['method'];
     if ($lazyFilterCheck && isset(static::$_lazyFilters[$class][$options['method']])) {
         $filters = static::$_lazyFilters[$class][$options['method']];
         unset(static::$_lazyFilters[$class][$options['method']]);
         $options['data'] = array_merge($filters, $options['data']);
         foreach ($filters as $filter) {
             $class::applyFilter($options['method'], $filter);
         }
     }
     $chain = new Filters($options);
     $next = $chain->rewind();
     return $next($class, $params, $chain);
 }
Example #29
0
 /**
  * Query
  *
  * @param mixed $sql
  * @param mixed $inputarr
  * @param mixed $numrows
  * @param mixed $offset
  * @access public
  * @return void
  */
 public function Query($sql, $inputarr = false, $numrows = -1, $offset = -1)
 {
     // auto add $dbprefix where we have {table}
     $sql = $this->_add_prefix($sql);
     // remove conversions for MySQL
     if (strcasecmp($this->dbtype, 'pgsql') != 0) {
         $sql = str_replace('::int', '', $sql);
         $sql = str_replace('::text', '', $sql);
     }
     $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
     if ($numrows >= 0 or $offset >= 0) {
         /* adodb drivers are inconsisent with the casting of $numrows and $offset so WE
          * cast to integer here anyway */
         $result = $this->dblink->SelectLimit($sql, (int) $numrows, (int) $offset, $inputarr);
     } else {
         $result = $this->dblink->Execute($sql, $inputarr);
     }
     if (!$result) {
         if (function_exists("debug_backtrace") && defined('DEBUG_SQL')) {
             echo "<pre style='text-align: left;'>";
             var_dump(debug_backtrace());
             echo "</pre>";
         }
         $query_params = '';
         if (is_array($inputarr) && count($inputarr)) {
             $query_params = implode(',', array_map(array('Filters', 'noXSS'), $inputarr));
         }
         die(sprintf("Query {%s} with params {%s} Failed! (%s)", Filters::noXSS($sql), $query_params, Filters::noXSS($this->dblink->ErrorMsg())));
     }
     return $result;
 }
Example #30
0
            $send = true;
        } else {
            $to_user = 0;
            $send = true;
        }
    }
    // Send message
    if (isset($send) && (!isset($_SESSION['chat_login']['last_send']) || isset($_SESSION['chat_login']['last_send']) && time() >= $_SESSION['chat_login']['last_send'])) {
        // Last message sent
        $_SESSION['chat_login']['last_send'] = $_SERVER['REQUEST_TIME'];
        // Delete old messages
        $messages = new MessagesModel();
        $messages->setCond('timestamp < "' . date('Y-m-d H:i:s', strtotime('-' . TIME_MESSAGE_OLD . ' minutes')) . '"');
        $messages->delete();
        // Data
        $data = new StdClass();
        $data->user = Filters::convert($_SESSION['chat_login']['user']);
        $data->id_user = $_SESSION['chat_login']['id_user'];
        $data->message = Filters::convert($message);
        $data->to_user = $to_user;
        $data->id_room = $_SESSION['chat_login']['id_room'];
        $data->reserved = $reserved;
        $data->timestamp = date('Y-m-d H:i:s');
        $fields = array_keys((array) $data);
        // Insert message
        $messages = new MessagesModel();
        $messages->setFields($fields);
        $messages->setData($data);
        $messages->insert();
    }
}