Location: PHPKode > projects > PhpProjectMaster > www/php/demo.php
<?php
/* 
 Demo management
 (c) 2004-2007 by "Oleg Savchuk" <hide@address.com>

 part of phpProjectMaster project
 http://phpprojmaster.sourceforge.net

 The contents of this file are subject to the GNU GENERAL PUBLIC LICENSE
 http://www.gnu.org/copyleft/gpl.html

 Hint: to create new module/script for new table, just :
 0. create new DB table 'newmodule' based on 'demo' table
 1. copy php/demo.php to php/newmodule.php and copy inc/demo.php to inc/newmodule.php
 2. 
  2.1. replace demo_link to related table name
  2.2. replace Demo in the scripts to your table/module name
 3. copy /template/admin/demo to /template/admin/newmodule
 4. replace Demo in all templates to whatever you need
 5. add new fields and remove unnecessary fields
*/

 session_start();
 require_once "../inc/sitelib.php" ;
 require_once "../inc/form_utils.php" ;
 require_once "../inc/image_utils.php" ;
 require_once "../inc/user.php" ;
 require_once "../inc/demo.lib.php" ;

 check_access(100);  //if you don't need this - you can also don't requite inc/user.php
 global_init();

//********* variables
 $tbl_name      = $demo_vars['table_name'];
 $tbl_key       = $demo_vars['table_key_id'];
 $item_id       = $_REQUEST['id']+0;

 $this_tpl_dir  = '/admin/demo';
 $tbl_fields    = 'cat_id email iname idesc fint ffloat fcombo_link fcombo_link2 fcombo fradio fyesno fdate_pop status'; //fields to save

//********* action!
 $CGI_ACTIONS=array(
  ''           => 'show_item_list',
  'SaveList'   => 'save_item_list',

  'AddNew'     => 'show_one_item',
  'Edit'       => 'show_one_item',
  'SaveRec'    => 'save_one_item',
  'DelRec'     => 'delete_item',

  'DelImg'     => 'delete_image',

 );

 go_action();

 exit;

//***************************
function show_item_list(){
 global $demo_vars;
 global $tbl_name, $tbl_key;
 global $this_script, $this_tpl_dir, $root_url, $MAX_PAGE_ITEMS;

 $moreurl=''; //additional url params for nav
 $where=" status<>127 ";

//******** filter options
 $page=get_page_option('page', $tbl_name."_lastpage");
 $pagenum=get_page_option('pagenum', $tbl_name."_pagenum");
 if (!$pagenum) $pagenum=$MAX_PAGE_ITEMS;
 $page_offset=$page*$pagenum;

//********** sorting
 $sortby=get_page_option('sortby', $tbl_name."_sortby", 'str');
 if (!$sortby) $sortby='iname';

 $SORTSQL=array(
    'id'        => 'demo_id',
    'iname'     => 'iname',
    'add_time'  => 'add_time',
 );

 $ordsql=$SORTSQL[$sortby];
//**********

 $search_str=$_REQUEST['s'];
 if ($search_str){
    $where.=" and (iname like ".dbq("%$search_str%")." 
               or idesc like ".dbq("%$search_str%")." 
    )";
    $moreurl.=(($moreurl)?'&':'').urlencode($search_str);
 }

 //get list of items
 $sql="select SQL_CALC_FOUND_ROWS * 
  from $tbl_name 
 where $where 
 order by $ordsql
 LIMIT $page_offset, $pagenum
 ";
 $rows=db_array($sql);
 $total_items=db_value("SELECT FOUND_ROWS()");
 foreach($rows as $k => $row){

    $rows[$k]=array_merge($row,array(
        'cat_id_name'      => db_value("select iname from demo_link where demo_link_id=".$row['cat_id']),
        'fcombo_link_name' => db_value("select email from demo where demo_id=".$row['fcombo_link']),
        'fdate_combo_human' => SQLDate2Str($row['fdate_combo'],1),

        'add_time_human' => SQLDate2Str($row['add_time'],1),
      ));
 }

 $list_nav='';
 if ($total_items>$pagenum){
//    $total_pages=ceil($total_items/$pagenum);

    $list_nav=make_List_Navigation($page, $total_items, $pagenum, "$this_script?".$moreurl."&page=", '', 'showall');
#    $list_nav=make_List_Navigation2($page, $total_items, $pagenum, "$this_script?".$moreurl."&page=");
 }

 $ps=array(
   'item_datarow' => $rows,
   'item_datarow_ctr' => count($rows),
   'list_navigation' => $list_nav,

//filters
   'search_str' => $search_str,
   'sortby'     => $sortby,
   'pagenum'    => $pagenum,
 );
 $ps=array_merge($ps, get_userinfo());
 parse_page($GLOBALS['this_tpl_dir']."/list", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//******* do action with checkboxed items
function save_item_list(){
 global $tbl_name, $tbl_key;

 $cbses=$_REQUEST['cb'];

 foreach($cbses as $item_id => $value){
   if (!$item_id) continue;

//   $hITEM=get_quotes($item_id);

   $IFORM=array(
     'status' => 127,
   );
   $sql="update $tbl_name set ".get_sqlupdate_set($IFORM).", upd_time=now(), upd_u_id=".$_SESSION['u_id']." where $tbl_key=$item_id";
//   rw($sql);
   db_query($sql);
 }

 show_item_list();
}


//***************************
//if $forceform=1 - redisplay values from FORM, not DB
function show_one_item($forceform=0){
 global $demo_vars;
 global $item_id, $tbl_key;
 $hITEMDB=array();

 $hITEM=$_REQUEST['item'];
 if (!$hITEM){  //if not set - this is initial form call - we can make here initializations

 }

 $item_id=$_REQUEST['id']+0;
 $hITEM[$tbl_key]=$item_id;
 if ($item_id){ #edit mode
    $hITEMDB=get_demo($item_id);
 }

 if ($forceform){
    $hITEM=array_merge($hITEMDB,$hITEM); //if redisplay from the FORM - merge with DB record, so read-only fields will be displayed too
    $hITEM['fdate_combo']=ComboDate2Str('fdate_combo');
 }else{
    if ($item_id){//only if Edit mode
       $hITEM=&$hITEMDB;  //making $hITEM same as $hITEMDB (no array copy)
    }
 }

 $ps=array(
   'select_cat_id'      => get_combo_select_sql("select demo_link_id, iname from demo_link where status=0 order by iname", $hITEM['cat_id']),
   'select_fcombo_link' => get_combo_select_sql("select demo_id, email from demo where status=0 order by email", $hITEM['fcombo_link']),
   'select_fcombo_link2'=> get_combo_select_sql("select demo_link_id, iname from demo_link where status=0 order by iname", $hITEM['fcombo_link2']),
   'fdate_pop_input'    => date2htmlInput_raw("item[fdate_pop]", $hITEM['fdate_pop']),
   'fdate_combo_input'  => date2htmlInput_combo("fdate_combo", $hITEM['fdate_combo']),

   'add_u_id_name'      => ($hITEM['add_u_id'])?get_user_name($hITEM['add_u_id']):'',
   'upd_u_id_name'      => ($hITEM['upd_u_id'])?get_user_name($hITEM['upd_u_id']):'',

//file/img upload
   'rand_str' => ($_REQUEST['is_rand'])?rand():'',
   'upload_url' => get_upload_url_demo($item_id),
   'upload_url_preview' => get_upload_url_demo($item_id,'preview'),
 );
 $ps=array_merge($ps, $hITEM);
 $ps=array_merge($ps, get_userinfo());
 parse_page($GLOBALS['this_tpl_dir']."/edit", $GLOBALS['PAGE_TPL_ADMIN'], $ps);
}

//*************************** save item info
function save_one_item(){
 global $demo_vars;
 global $tbl_name, $tbl_key, $tbl_fields;
 $item_id=$_REQUEST['id']+0;

 if (validate_item($item_id, $_REQUEST['item'])){
    $hITEM=get_demo($item_id);

    //read from form only necessary/allowed fields
    $IFORM=form2dbhash($_REQUEST['item'], "$tbl_fields");

    //make some adjustments
    //add new text to 'combo+text'
    if (!$IFORM['fcombo_link2'] && $_REQUEST['item']['new_fcombo_link2']) {
       $IFORM['fcombo_link2']=insert_demo_link($_REQUEST['item']['new_fcombo_link2']);
    }
    //convert date from human str to SQL format
    $IFORM['fdate_pop']=StrDate2SQL($IFORM['fdate_pop']);
    //convert 3 combo date to one value
    $IFORM['fdate_combo']=StrDate2SQL(ComboDate2Str('fdate_combo', $_REQUEST['item']));

    if ($item_id){  //id exists - update record
       if (!$IFORM['pwd']) unset($IFORM['pwd']);  //special field - don't update if no value

       $IFORM['upd_u_id']=$_SESSION['u_id'];

       $sql="update $tbl_name set ".get_sqlupdate_set($IFORM).", upd_time=now() where $tbl_key=$item_id";
//       logger($sql);
       db_query($sql);
   
       $GLOBALS['green_msg']=lng("Record has been modified");
    } else {     //id not exits - insert record
       $IFORM['add_u_id']=$_SESSION['u_id'];

       $sql="insert into $tbl_name ".get_sqlinsert_set($IFORM,', add_time',', now()');
//       logger($sql);
       $sth=db_query($sql);
       $item_id=get_identity();
   
       $GLOBALS['green_msg']=lng("New Record has been added");
    }
    $_REQUEST['id']=$item_id;


    //****** perform upload attached file (if present)
    $res=upload_file($item_id, 'file1', 
                     array('gif', 'jpg', 'png'), 
                     $demo_vars['upload_path'],
                     array(
                       'preview' => 1,
#                       'preview_maxw'   => $GLOBALS['MAX_PREVIEW_IMG_WIDTH'],
#                       'preview_maxh'   => $GLOBALS['MAX_PREVIEW_IMG_HEIGHT'],
                       'resize' => 1,
#                       'resize_maxw'    => $GLOBALS['MAX_FULL_IMG_WIDTH'],
#                       'resize_maxh'    => $GLOBALS['MAX_FULL_IMG_HEIGHT'],
                    ));
    if ($res<0){ #error - upload failed
    }elseif($res>0){ #upload successfull
       $_REQUEST['is_rand']=1;       
    }else{ #no file specified (empty upload)
    }
    //****** upload end

    if ($_REQUEST['AndAddNext']){
       unset($_REQUEST['item']);
       unset($_REQUEST['id']);
    }
    show_one_item();
 } else {
    show_one_item(1);
 }

}

//################# Validate item form values in IFORM
function validate_item($item_id=0, $IFORM){
 global $demo_vars, $err_msg;

 $REQFLD=array(
'cat_id'  => lng('Category'),
'iname'   => lng('Name'),
'email'   => lng('Email'),
);

// if (!$item_id) $REQFLD['xxx']=lng('xxx');  //add validation only for Edit mode

 //VALIDATE REQUIRED FIELDS
 if (!$err_msg) { $err_msg=validate_form($IFORM, $REQFLD); }

 //VALIDATE if field unique
 if (!$err_msg && is_dbrecord_exists2($GLOBALS['tbl_name'], 'email', $IFORM['email'], " and ".$GLOBALS['tbl_key']."<>$item_id and status<>127") ){
    $err_msg=lng("Such Email already exists. Please, select another.");
 }

 if ($err_msg) { return 0 ;}
 return 1;
}

//************************
function delete_item(){
 $item_id=$_REQUEST['id']+0;

 delete_demo($item_id);

 show_item_list();
}

//************* remove uploaded image
function delete_image(){
 global $demo_vars;

 $item_id=$_REQUEST['id']+0;

 cleanup_upload($item_id, $demo_vars['upload_path']);

 show_one_item();
}


?>
Return current item: PhpProjectMaster