eesyphp/example/includes/db.php

391 lines
9.5 KiB
PHP
Raw Normal View History

2020-04-18 00:51:33 +02:00
<?php
use EesyPHP\App;
2023-01-30 11:23:35 +01:00
use EesyPHP\Db;
2023-01-29 19:57:26 +01:00
use EesyPHP\Hook;
use EesyPHP\Log;
2023-01-29 19:57:26 +01:00
use Unidecode\Unidecode;
2023-01-30 11:23:35 +01:00
$db = new Db(
App::get('db.dsn', null, 'string'),
App::get('db.user', null, 'string'),
App::get('db.password', null, 'string'),
App::get('db.options', array(), 'array'),
App::get('db.date_format', null, 'string'),
App::get('db.datetime_format', null, 'string'),
2023-01-30 11:23:35 +01:00
);
2020-04-18 00:51:33 +02:00
/*
* Methods to handle items
*/
function get_items($orderby='id', $raw_values=false) {
2023-01-30 11:23:35 +01:00
global $db;
2020-04-18 00:51:33 +02:00
try {
$info = $db -> get_many('item', null, null, $orderby);
if (!is_array($info))
return;
if ($raw_values)
return $info;
2020-04-18 00:51:33 +02:00
$items = array();
foreach ($info as $item)
$items[$item['id']] = $db -> format_row_info($item, array('date'));
return $items;
2020-04-18 00:51:33 +02:00
}
catch (Exception $e) {
Log :: error("Error retreiving items info from database : ".$e->getMessage());
2020-04-18 00:51:33 +02:00
}
return false;
}
function get_item($id, $raw_values=false) {
2023-01-30 11:23:35 +01:00
global $db;
2020-04-18 00:51:33 +02:00
try {
$info = $db -> get_one('item', array('id' => $id));
2020-04-18 00:51:33 +02:00
if (!is_array($info))
return false;
if ($raw_values)
return $info;
2020-04-18 00:51:33 +02:00
return $db -> format_row_info($info, array('date'));
2020-04-18 00:51:33 +02:00
}
catch (Exception $e) {
Log :: error("Error retreiving item #$id info from database : ".$e->getMessage());
2020-04-18 00:51:33 +02:00
}
return false;
}
function add_item($values) {
2023-01-30 11:23:35 +01:00
global $db;
$values['date'] = $db -> time2datetime(time());
2020-04-18 00:51:33 +02:00
try {
2023-01-30 11:23:35 +01:00
$result = $db -> fpdo -> insertInto('item')
-> values($values)
-> execute();
2020-04-18 00:51:33 +02:00
if ($result !== false) {
$item = get_item($result);
Log :: info("New item #$result added");
2023-01-29 19:57:26 +01:00
Hook :: trigger('item_added', $item);
2020-04-18 00:51:33 +02:00
return $item;
}
}
catch (Exception $e) {
Log :: error("Error creating item in database : ".$e->getMessage());
2020-04-18 00:51:33 +02:00
}
return false;
}
function update_item($id, $changes) {
2023-01-30 11:23:35 +01:00
global $db;
2020-04-18 00:51:33 +02:00
if (!is_array($changes))
return false;
if (empty($changes))
return true;
$item = get_item($id, true);
if (!is_array($item)) return false;
if (isset($changes['date']) && $changes['date'])
2023-01-30 11:23:35 +01:00
$changes['date'] = $db -> time2datetime($changes['date']);
2020-04-18 00:51:33 +02:00
try {
2023-01-30 11:23:35 +01:00
$result = $db -> fpdo -> update('item')
-> set($changes)
-> where('id', $id)
-> execute();
2020-04-18 00:51:33 +02:00
if ($result !== false) {
Log :: info("Item #$id updated");
2023-01-29 19:57:26 +01:00
Hook :: trigger('item_updated', $item);
2020-04-18 00:51:33 +02:00
return true;
}
}
catch (Exception $e) {
Log :: error("Error updating item #$id in database : ".$e->getMessage());
2020-04-18 00:51:33 +02:00
}
return false;
}
function change_item_status($id, $status) {
2022-04-24 17:43:44 +02:00
if (update_item($id, array('status' => $status))) {
Log :: info("Status of item #$id changed to $status.");
2022-04-24 17:43:44 +02:00
return true;
}
return false;
2020-04-18 00:51:33 +02:00
}
function archive_item($id) {
2022-04-24 17:43:44 +02:00
return change_item_status($id, 'archived');
2020-04-18 00:51:33 +02:00
}
function delete_item($id) {
2023-01-30 11:23:35 +01:00
global $db;
2020-04-18 00:51:33 +02:00
try {
2023-01-30 11:23:35 +01:00
$result = $db -> fpdo -> deleteFrom('item')
-> where('id', $id)
-> execute();
2020-04-18 00:51:33 +02:00
if ($result !== false) {
Log :: info("Item #$id deleted");
2020-04-18 00:51:33 +02:00
return True;
}
}
catch (Exception $e) {
Log :: error("Error deleting item #$id from database : ".$e->getMessage());
2020-04-18 00:51:33 +02:00
}
return false;
}
function search_items($params) {
global $db;
2020-04-18 00:51:33 +02:00
// Detect PgSQL backend
$is_pgsql = (strpos(App::get('db.dsn', '', 'string'), "pgsql:") === 0);
2020-04-18 00:51:33 +02:00
$where = array();
if (isset($params['status']) && $params['status'] && $params['status'] != 'all')
$where['status'] = $params['status'];
$patterns_where = array();
if (isset($params['pattern']) && $params['pattern']) {
foreach(preg_split('/\s+/', trim($params['pattern'])) as $word) {
if (!$word) continue;
$patterns_word=array();
// If numeric pattern ?
if (preg_match('/^[0-9]+$/', $word)) {
// Numeric pattern
$word = intval($word);
$patterns_word['id = ?'] = $word;
}
else {
// Text pattern
foreach (array('name', 'description') as $field) {
if ($is_pgsql) {
$word = Unidecode::unidecode($word);
2020-04-18 00:51:33 +02:00
$patterns_word["unaccent($field) ILIKE ?"] = "%$word%";
}
else
$patterns_word["$field LIKE ?"] = "%$word%";
}
}
$patterns_where[] = $patterns_word;
}
}
$order='id';
$orders=array('id', 'name', 'date', 'status', 'description');
if (isset($params['order'])) {
if (!in_array($order, $orders))
return -1;
$order=$params['order'];
}
$order_direction='DESC';
if (isset($params['order_direction']) && $params['order_direction']) {
if (!in_array($params['order_direction'], array('ASC', 'DESC')))
return -1;
$order_direction=$params['order_direction'];
}
$orderby="$order $order_direction";
$limit = "";
$page = 1;
$nb_by_page = 10;
2020-04-18 00:51:33 +02:00
$offset = 0;
if (!isset($params['all'])) {
if (isset($params['page']) && $params['page']>0) {
if (isset($params['nb_by_page']) && $params['nb_by_page']>0) {
$nb_by_page = intval($params['nb_by_page']);
2020-04-18 00:51:33 +02:00
}
$page = intval($params['page']);
2020-04-18 00:51:33 +02:00
}
$offset = ($page-1)*$nb_by_page;
$limit = $nb_by_page;
2020-04-18 00:51:33 +02:00
}
try {
2023-01-30 11:23:35 +01:00
$query = $db -> fpdo -> from('item');
2020-04-18 00:51:33 +02:00
if (!empty($where))
$query -> where($where);
foreach ($patterns_where as $patterns_word)
2022-04-24 17:43:44 +02:00
call_user_func_array(
array($query, 'where'),
array_merge(
array('('.implode(' OR ', array_keys($patterns_word)).')'),
array_values($patterns_word)
)
);
2020-04-18 00:51:33 +02:00
$result = $query -> orderBy($orderby)
-> limit($limit)
-> offset($offset)
-> execute();
if ($result === false) {
Log :: error('search_items() : search in DB return false');
return false;
}
$rows = $result -> fetchAll();
$items = array();
foreach ($rows as $row) {
2023-01-30 11:23:35 +01:00
$items[] = $db -> format_row_info($row, array('date'));
}
if (isset($params['all'])) {
return array(
'count' => count($items),
'first' => 1,
'last' => count($items),
'nb_pages' => 1,
'page' => 1,
'items' => $items
);
}
2023-01-30 11:23:35 +01:00
$query_count = $db -> fpdo -> from('item')
-> select(null)
-> select('count(*) as count');
if (!empty($where))
$query_count -> where($where);
foreach ($patterns_where as $patterns_word)
call_user_func_array(
array($query_count, 'where'),
array_merge(
array('('.implode(' OR ', array_keys($patterns_word)).')'),
array_values($patterns_word)
)
);
$result_count = $query_count -> execute();
if ($result_count === false) {
Log :: debug('search_items() : search for count in DB return false');
return False;
}
$count = $result_count -> fetch();
return array(
'count' => $count['count'],
'first' => $offset+1,
'last' => (
$offset+$nb_by_page<$count['count']?
$offset+$nb_by_page:$count['count']),
'nb_pages' => ceil($count['count']/$nb_by_page),
'page' => $page,
'items' => $items,
);
2020-04-18 00:51:33 +02:00
}
catch (Exception $e) {
Log :: exception(
$e, "An exception occured searching items with params %s infos from database : ",
preg_replace("/\n[ \t]*/", " ", print_r($params, true))
);
2020-04-18 00:51:33 +02:00
}
return false;
}
function export_items($fd=null) {
2022-04-24 17:43:44 +02:00
if (!$fd) $fd = fopen('php://output', 'w');
fputcsv(
$fd,
array (
'id',
'name',
'date',
'status',
'description',
)
);
$items = get_items();
foreach($items as $item) {
fputcsv(
$fd,
array(
$item['id'],
$item['name'],
$item['date'],
$item['status'],
$item['description'],
)
);
}
return True;
2020-04-18 00:51:33 +02:00
}
function restore_items($fd=null) {
2023-01-30 11:23:35 +01:00
global $db;
2022-04-24 17:43:44 +02:00
if (!$fd) $fd = fopen('php://stdin', 'r');
try {
2023-01-30 11:23:35 +01:00
$result = $db -> fpdo -> deleteFrom('item')
-> execute();
2022-04-24 17:43:44 +02:00
if ($result === false) {
Log :: error("An unknown error occured truncating item table in database.");
2022-04-24 17:43:44 +02:00
return false;
}
}
catch (Exception $e) {
Log :: error("Error truncating item table in database : ".$e->getMessage());
2022-04-24 17:43:44 +02:00
return false;
}
$first_row = false;
$line = 0;
$restored = 0;
$error = false;
$datetime_fields = array (
'date',
);
// Map fields to support hold CSV files format
$mapping = array (
'creation_date' => 'date',
'desc' => 'description',
);
while (($row = fgetcsv($fd)) !== FALSE) {
$line++;
if ($first_row === false) {
$first_row = $row;
continue;
}
try {
$values = array();
for ($i=0; $i < count($first_row); $i++) {
if (!$row[$i]) continue;
$field = (
array_key_exists($first_row[$i], $mapping)?
$mapping[$first_row[$i]]:
$first_row[$i]);
2023-01-30 11:23:35 +01:00
$value = (in_array($field, $datetime_fields)?$db -> time2datetime($row[$i]):$row[$i]);
2022-04-24 17:43:44 +02:00
$values[$field] = $value;
}
2023-01-30 11:23:35 +01:00
$result = $db -> fpdo -> insertInto('item')
-> values($values)
-> execute();
2022-04-24 17:43:44 +02:00
if ($result !== false) {
$restored++;
}
else {
Log :: error("Unkwown error occured restoring item from line #$line :\n".print_r($values, true));
2022-04-24 17:43:44 +02:00
$error = true;
}
}
catch (Exception $e) {
Log :: error(
2022-04-24 17:43:44 +02:00
"Error restoring item from line #$line : ".$e->getMessage()."\n".print_r($values, true));
$error = true;
}
}
Log :: info("$restored items restored");
2022-04-24 17:43:44 +02:00
// Trigger hooks
2023-01-29 19:57:26 +01:00
Hook :: trigger('items_restored');
2022-04-24 17:43:44 +02:00
return !$error;
2020-04-18 00:51:33 +02:00
}
# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab