php /*! \mainpage InstantDbApp.php * InstantDbApp - Instant DB Application class & support functions You want to build a web database application? You want to do it quickly? You want to do it simple? You want your database application to be customizable; you want to be able to change HTML behind your dynamic web pages easily and with no impact on business logic? You want to be able to add more features in the future with no need to re-write your code? All you need is InstantDbApp class. InstantDbApp class provides basic functionality for displaying data from database in list format, with pagination and sorting by columns, and for displaying a form for editing a single record. It uses HTML templates for displaying data, in list or single record formats, so you can easily change a look of your pages. But it does more than that: it creates the first draft of this templates, so you don’t need to learn this new template language, you can just take what InstantDbApp class gives you and use them without any changes. Or change just those pieces of HTML code you are familiar with. Click here for a quick start tutorial Click here to download */ /*! \file InstantDbApp.php * \brief Instant DB Application class & support functions */ session_write_close(); //! Instant DB Application class. version 0.3.012a class InstantDbApp { //! \publicsection var $original_url; //!< readonly, original URL var $original_query; //!< readonly, original QUERY_STRING var $original_request; //!< readonly, original $_REQUEST var $reusing; //!< readonly, true if saved instance is used var $exit_edit_url; //!< r/w, URL to exit from 'edit' var $exit_view_url; //!< r/w, URL to exit from 'view' var $userdata; //!< r/w, to save arbitrary user data var $readonly; //!< r/w var $edit_readonly; var $on_read; //!< read event handler /*!< on_read($this,&$resRow,$why)); */ var $onRead; //!< read event handler /*!< onRead(&$resRow,$why)); */ var $on_init_record; //!< init record event handler /*!< on_init_record($this,&$resRow); (==on_read($this,&$resRow,'init')) */ var $onInitRecord; //!< init record event handler /*!< onInitRecord(&$resRow); (==onRead(&$resRow,'init')) */ var $on_validate; //!< validate event handler /*!< $r = on_validate($this,&$post,&$errors_array); - $r==0 - not validated */ var $onValidate; //!< validate event handler /*!< $r = onValidate(&$post,&$errors_array); - $r==0 - not validated */ var $on_validate_field; var $on_delete; //!< delete event handler /*!< $r = on_delete($this,$pk,&$errors_array); - $r==0 - do not proceed with deletion */ var $onDelete; //!< delete event handler /*!< $r = onDelete($pk,&$errors_array); - $r==0 - do not proceed with deletion */ var $on_after_delete; //!< afterdelete event handler /*!< on_after_delete($this,$pk); */ var $onAfterDelete; //!< afterdelete event handler /*!< onAfterDelete($pk); */ var $on_save; //!< save event handler /*!< $r = on_save($this,&$post); - $r==0 - do not proceed with saving */ var $onSave; //!< save event handler /*!< $r = onSave(&$post); - $r==0 - do not proceed with saving */ var $on_after_save; //!< aftersave event handler /*!< on_after_save($this,&$post); */ var $onAfterSave; //!< aftersave event handler /*!< onAfterSave(&$post); */ var $on_read_list_row; //!< readlistrow event handler /*!< on_read_list_row($this,$i,&$row); */ var $onReadListRow; //!< readlistrow event handler /*!< onReadListRow($i,&$row); */ var $on_read_field; //!< readfield event handler /*!< $r = on_read_field($this,$when,$f,&$val); - $r==0 - do not proceed with autoformat */ var $onReadField; //!< readfield event handler /*!< $r = onReadField($when,$f,&$val); - $r==0 - do not proceed with autoformat */ var $on_get_list_count; //!< getlistcount event handler /*!< $r = on_get_list_count($this); - isset($r) - do not proceed with standard sql for count */ var $onGetListCount; //!< getlistcount event handler /*!< $r = onGetListCount($this); - isset($r) - do not proceed with standard sql for count */ var $on_read_list_all; //!< readlistall event handler var $onReadListAll; //!< readlistall event handler /*!< $r = onReadListAll($this,&$count,&$result_array) - $r=null or $count=null or $res=null - need to process - $r=0 - processed, but post-process needed - $r=1 - nothing more needed */ var $on_dberr; var $on_filter; //!< filter event handler ($this) var $onGetPage; //!< getpage event handler /*!< $page = onGetPage($pagename); \n usually set $onGetPage to 'get_template' when working with cmsite */ var $on_get_encryption_key; var $on_start; var $on_render; var $on_exit_edit; var $recordRes; var $par; var $page; var $table; var $list_post; var $process_name; var $last_process_name; var $usedata; var $autovars; var $filter_data; var $upload_dir; var $saved_edit_post; //! \privatesection var $listfields; var $listDistinct; var $pk; var $pageLinksCount=20; var $listCount; var $listRes; var $where; var $where_and_array; var $orderby; var $groupby; var $having; var $page_requested; var $lastListSql; var $sort; var $errors; var $lang='en'; var $sortUpInd = '↑'; var $sortDnInd = '↓'; var $noSortInd = ' '; var $upload; //! \publicsection ############################################################################ //! Constructor function InstantDbApp( $par //!< param array: /*!< - table: table name - name: names InstantDbApp instance, table name by default - fields: field array - listFields: field to show in list - fieldOptions: array (fieldname=> options array) - editHtml: html template - listHtml: html template - outerHtml: html template - sort: field to sort - debug: 0 / 1 / 5... - generate_edit: 0/1 - generate_list: 0/1 */ ) { if (!$par) { $this->printUsage(); return; } if (gettype($par)=='string') { $this->printTableFields($par); return; } if ($par['generate_fields']) { $this->printTableFields($par['table']); return; } $name = $par['name'] ? $par['name'] : $par['table']; if (isset($par['use_session']) && (!$par['use_session'])) { if ($par['debug']>=5) echo "Not using sessions
"; } else { session_start(); $dbbb = & $_SESSION[$name]; } if ($dbbb && ($par['continue'] || (!$_REQUEST['reread'] && ( $_SERVER['REQUEST_METHOD']=='POST' || $_REQUEST['continue'] || isset($_REQUEST['page']) || isset($_REQUEST['sort']) || isset($_REQUEST['do_edit']) || isset($_REQUEST['do_delete']) || isset($_REQUEST['do_add']) || isset($_REQUEST['do_clone']) || isset($_REQUEST['do_cancel']) || isset($_REQUEST['do_reset']) || isset($_REQUEST['do_filter']) || isset($_REQUEST['do_view']) || isset($_REQUEST['do_suspend_edit']) || isset($_REQUEST['do_resume_edit']) ) ) ) ) { $this->clone2this($dbbb); $this->reusing = 1; if ($this->par['debug']) { echo "Reusing!
"; } } else { $this->par = $par; $this->reusing = 0; if ($this->par['debug']) { echo "Creating!
"; } $this->original_url=$_SERVER['PHP_SELF']; $this->original_request=$_REQUEST; $this->original_query=$_SERVER['QUERY_STRING']; $this->readonly = $this->par['readonly']; } if ($this->par['debug']>=10) { echo "
";
      print_r ($this->par);
      echo "

"; } if (isset($par['use_session']) && (!$par['use_session'])) ; else $_SESSION[$name] = & $this; $this->init(); } ############################################################################ function get($name) { session_start(); $dbbb = & $_SESSION[$name]; return $dbbb; } ############################################################################ //! \private function clone2this($that) { $this->original_url = $that->original_url; $this->original_query = $that->original_query; $this->original_request = $that->original_request; $this->reusing = $that->reusing; $this->exit_edit_url = $that->exit_edit_url; $this->exit_view_url = $that->exit_view_url; $this->userdata = $that->userdata; $this->readonly = $that->readonly; $this->edit_readonly = $that->edit_readonly; $this->onRead = $that->onRead; $this->onInitRecord = $that->onInitRecord; $this->onValidate = $that->onValidate; $this->onDelete = $that->onDelete; $this->onAfterDelete = $that->onAfterDelete; $this->onSave = $that->onSave; $this->onAfterSave = $that->onAfterSave; $this->onReadListRow = $that->onReadListRow; $this->onReadField = $that->onReadField; $this->onGetListCount = $that->onGetListCount; $this->onReadListAll = $that->onReadListAll; $this->onGetPage = $that->onGetPage; $this->on_read = $that->on_read; $this->on_init_record = $that->on_init_record; $this->on_validate = $that->on_validate; $this->on_validate_field = $that->on_validate_field; $this->on_delete = $that->on_delete; $this->on_after_delete = $that->on_after_delete; $this->on_save = $that->on_save; $this->on_after_save = $that->on_after_save; $this->on_read_list_row = $that->on_read_list_row; $this->on_read_field = $that->on_read_field; $this->on_get_list_count = $that->on_get_list_count; $this->on_read_list_all = $that->on_read_list_all; $this->on_filter = $that->on_filter; $this->on_dberr = $that->on_dberr; $this->on_start = $that->on_start; $this->on_render = $that->on_render; $this->on_exit_edit = $that->on_exit_edit; $this->on_get_encryption_key = $that->on_get_encryption_key; $this->par = $that->par; $this->listfields = $that->listfields; $this->listDistinct = $that->listDistinct; $this->pk = $that->pk; $this->pageLinksCount = $that->pageLinksCount; $this->listCount = $that->listCount; $this->listRes = $that->listRes; $this->where = $that->where; $this->where_and_array = $that->where_and_array; $this->orderby = $that->orderby; $this->groupby = $that->groupby; $this->having = $that->having; $this->page_requested = $that->page_requested; $this->lastListSql = $that->lastListSql; $this->page = $that->page; $this->sort = $that->sort; $this->errors = $that->errors; $this->lang = $that->lang; $this->sortUpInd = $that->sortUpInd; $this->sortDnInd = $that->sortDnInd; $this->noSortInd = $that->noSortInd; $this->recordRes = $that->recordRes; $this->table = $that->table; $this->list_post = $that->list_post; $this->usedata = $that->usedata; $this->autovars = $that->autovars; $this->filter_data = $that->filter_data; $this->process_name = $that->process_name; $this->last_process_name = $that->last_process_name; $this->upload_dir = $that->upload_dir; $this->saved_edit_post = $that->saved_edit_post; } ############################################################################ //! \private function printUsage() { $www = 'http://www.softmaster.co.uk/products/InstantDbApp'; echo<<
\$ida = & new InstantDbApp( [table name] );

Please go to $www for instrustions EOD; } ############################################################################ //! \private function printTableFields($t=null) { if (!$t) $t = $this->table; echo '
';
    echo '$ida = & new InstantDbApp( array(',"\n";
    echo "  'table'=>'$t',\n";
    /*
    $res = db_getAll("describe $t");
    foreach ($res as $r) {
      $s .= "'{$r['Field']}',";
      $o[$r['Field'].'_x'] = array('Type'=>$r['Type'],'Null'=>$r['Null'],'Key'=>$r['Key'],'Default'=>$r['Default']);
    }
    */
    $res=db_tableInfo($t);
    $s='';
    foreach ($res as $r) {
      // pdebug($r['flags']);
      $f = strtolower($r['name']);
      $null = preg_match('/not_null/',$r['flags'])? 0:1;
      $pk = preg_match('/primary_key/',$r['flags'])? 1:0;
      $s .= "'$f',";
      $o[$f] = array('Type'=>$r['type'],'Len'=>$r['len'],'Null'=>$null,'PK'=>$pk,'Default'=>$r['default'],'Caption'=>$f,'Format'=>'');
    }
    $s = rtrim($s,',');
    echo  "  'fields'=>array($s),\n";
    echo "  'listFields'=>array($s),\n";
    echo "  'fieldOptions'=>array(\n";

    foreach (array_keys($o) as $ko) {
      $so .= "    '$ko'=>array(";
      foreach (array_keys($o[$ko]) as $kko) {
        if ($o[$ko][$kko] === '' or $o[$ko][$kko] === null)
          $so .= "'$kko'=>null,";
        else
          $so .= "'$kko'=>'".$o[$ko][$kko]."',";
      }
      $so = rtrim($so,',');
      $so .= "),\n";
    }
    $so = rtrim($so,",\n");
    $so .= "\n  )\n";
    $so .= "  ,'debug' => 0\n";
    $so .= "  ,'generate_list' => 0\n";
    $so .= "  ,'generate_edit' => 0\n";
    $so .= "  ,'editHtml' => null\n";
    $so .= "  ,'listHtml' => null\n";
    $so .= "  ,'outerHtml' => null\n";
    $so .= "  ,'pagesize' => 20\n";
    $so .= "));\n";
    $so .= '$ida->process($_REQUEST);' . "\n";
    echo $so;
    echo '

'; } ############################################################################ //! \private function init() { ## todo if (! $this->par['fields']) $this->par['fields'] = array_keys($this->par['fieldOptions']); #if (! $this->listfields) $this->listfields = $this->par['listFields']; #if (! $this->listfields) $this->listfields = $this->par['fields']; if (! $this->par['listFields']) $this->par['listFields'] = $this->par['fields']; if (! $this->pk) $this->pk = $this->getPK(); if (! $this->sort) $this->sort = $this->par['sort']; if (! $this->listDistinct) $this->listDistinct = $this->par['listDistinct']; if (! $this->table) $this->table = $this->par['table']; if (! $this->par['upload_dir']) $this->par['upload_dir'] = "upload_dir/{$this->table}"; if (! $this->upload_dir) $this->upload_dir = $this->par['upload_dir']; } ############################################################################ //! save or get usedata function save_get_userdata($name,$val=null) { if ($val!==null) { $this->userdata[$name] = $val; return $val; } else { return $this->userdata[$name]; } } ############################################################################ //! save usedata function save_userdata($name,$val=null) { $this->userdata[$name] = $val; return $val; } ############################################################################ //! get usedata function get_userdata($name) { return $this->userdata[$name]; } ############################################################################ //! save autovar function save_autovar($name,$val=null) { $this->autovars[$name] = $val; return $val; } ############################################################################ //! private function process_autovars() { global $_VARS; if ($this->autovars) { foreach(array_keys($this->autovars) as $v) { $_VARS[$v] = $this->autovars[$v]; } } } ############################################################################ //! Main function - does all function process( $post=null //!< usually $_REQUEST ) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: process (",$post,")
"; } $this->last_process_name = $this->process_name; if ( $post['do_edit'] || $post['do_save'] || $post['do_saveexit'] || $post['do_delete'] || $post['do_add'] || $post['do_clone'] || $post['do_reset'] || $post['do_cancel'] || $post['do_suspend_edit'] || $post['do_resume_edit'] ) { $this->expose_filter(); // just in case $this->processEdit($post); } else if ($post['do_view']) { $this->expose_filter(); // just in case $this->processView($post); } else { // expose_filter() - inside $this->processList($post); } } ############################################################################ //! process 'edit' screen function process_edit($post /*!< usually $_REQUEST */,$pk=null ) { if ($this->reusing) $pk = null; return $this->processEdit($post,$pk); } ############################################################################ //! process 'add' screen function process_add($post /*!< usually $_REQUEST */,$pk=null ) { if (!$this->reusing) $post['do_add'] = 1; return $this->processEdit($post); } ############################################################################ //! process 'view' screen function process_view($post /*!< usually $_REQUEST */,$pk=null ) { if ($this->reusing) $pk = null; return $this->processView($post,$pk); } ############################################################################ //! process 'list' screen function process_list($post /*!< usually $_REQUEST */) { return $this->processList($post); } ############################################################################ //! process 'edit' screen function processEdit($post /*!< usually $_REQUEST */,$pk=null ) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: processEdit (",$post,") pk='$pk' (last_process_name: {$this->last_process_name} )
"; } //if (! isset ($post) ) $post = $_REQUEST; $this->process_name = 'edit'; $this->process_autovars(); if ($this->on_start) { $func = $this->on_start; $r = $func($this,$post); if (!$r) return; } if ($pk !== null) $post['db_'.$this->pk] = $pk; if (!$this->exit_edit_url) #$this->exit_edit_url = $this->original_url . '?continue=1'; $this->exit_edit_url = append_url($this->original_url,'continue=1'); if ($this->par['debug']>=5) { echo ": exit_edit_url = ",$this->exit_edit_url,"
"; } $is_new = 0; $this->recordRes = null; $this->errors = null; if ($post['do_save'] || $post['do_saveexit']) { if ($this->par['debug']>=5) { echo "Call: processEdit - save&save&exit
"; } if (($goodpost = $this->validate($post)) and $this->save($goodpost)) { if ($post['do_saveexit']) { $r = 1; if ($this->on_exit_edit) { $func = $this->on_exit_edit; $r = $func($this,'saveexit',$post); } if ($r) redirect($this->exit_edit_url); exit(); } else { $this->readRecord($goodpost['db_'.$this->pk],1); } } else { if ($this->par['debug']>=5) { echo "Call: processEdit - not validated
"; } $this->recordRes = $this->readRecordFromPost($post,1); #&& $is_new = $post['is_new']; $not_validated = 1; } } else if ($post['do_add']) { $is_new = 1; $this->recordRes = $this->initRecord(1); } else if ($post['do_clone']) { $this->readRecord($post['db_'.$this->pk],1,'clone'); $this->recordRes[$this->pk] = null; $is_new = 1; } else if ($post['do_cancel']) { $r = 1; if ($this->on_exit_edit) { $func = $this->on_exit_edit; $r = $func($this,'cancel',$post); } if ($r) redirect($this->exit_edit_url); exit(); } else if ($post['do_delete']) { if ($this->deleteRecord($post['db_'.$this->pk])) { $r = 1; if ($this->on_exit_edit) { $func = $this->on_exit_edit; $r = $func($this,'delete',$post); } if ($r) redirect($this->exit_edit_url); exit(); } else { if ($this->last_process_name=='list') { $this->showErrorPage($this->errors,$this->exit_edit_url); exit(); } else { $this->readRecord($post['db_'.$this->pk],1); } } } ## todo else if ($post['do_suspend_edit']) { $this->saved_edit_post = $post; $r = 1; if ($this->on_exit_edit) { $func = $this->on_exit_edit; $r = $func($this,'suspend',$post); } if ($r) redirect($this->exit_edit_url); exit(); } else if ($post['do_resume_edit']) { if ($this->saved_edit_post) { $this->recordRes = $this->readRecordFromPost($this->saved_edit_post,1); #&& $is_new = $this->saved_edit_post['is_new']; } else { redirect($this->exit_edit_url); exit(); } } else ## if ($post['do_reset'] || $post['do_edit']) || null - may be called directly { $this->readRecord($post['db_'.$this->pk],1); } $_VARS['url']=$this->original_url; $_VARS['exit_url']=$this->exit_edit_url; $_VARS['errors'] = null; if ($this->errors) $_VARS['errors'] = join('
',$this->errors); $_VARS['not_validated'] = $not_validated; $_VARS['is_new'] = $is_new; $_VARS['res']=$this->recordRes; $_VARS['mode']='edit'; $_VARS['readonly'] = null; $_VARS['cantadd'] = null; $_VARS['cantdel'] = null; if ($this->readonly) { $_VARS['readonly'] = 'readonly'; $_VARS['cantadd'] = 1; # ? master $_VARS['cantdel'] = 1; # } if ($this->edit_readonly) { $_VARS['readonly'] = 'readonly'; } if ($this->cantadd) $_VARS['cantadd'] = 1; if ($this->cantdel) $_VARS['cantdel'] = 1; if ($this->on_render) { $func = $this->on_render; $r = $func($this,$post); if (! $r) return; } $this->showHtmlPageWithContent($this->par['editHtml']?'':$this->DefaultEdit(),$this->par['editHtml'],$this->par['outerHtml']); if ($this->par['generate_edit']) { echo "
Edit template:"; echo "
";
      echo  $this->defaultEditTemplate(1);
      echo "

"; } } ############################################################################ //! process 'view' screen function processView($post /*!< usually $_REQUEST */,$pk=null ) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: processView (",$post,") (last_process_name: {$this->last_process_name} )
"; } //if (! isset ($post) ) $post = $_REQUEST; $this->process_name = 'view'; $this->process_autovars(); if ($this->on_start) { $func = $this->on_start; $r = $func($this,$post); } if ($pk !== null) $post['db_'.$this->pk] = $pk; if (!$this->exit_edit_url) #$this->exit_edit_url = $this->original_url . '?continue=1'; $this->exit_edit_url = append_url($this->original_url,'continue=1'); if (!$this->exit_view_url) { if ($this->exit_edit_url) $this->exit_view_url = $this->exit_edit_url; else #$this->exit_view_url = $this->original_url . '?continue=1'; $this->exit_view_url = append_url($this->original_url,'continue=1'); } $this->readRecord($post['db_'.$this->pk],1); $_VARS['url']=$this->original_url; $_VARS['exit_url']=$this->exit_view_url; $_VARS['res']=$this->recordRes; $_VARS['mode']='view'; $_VARS['readonly'] = 'readonly'; $_VARS['cantadd'] = 1; if ($this->on_render) { $func = $this->on_render; $r = $func($this,$post); if (! $r) return; } $this->showHtmlPageWithContent($this->par['viewHtml']?'':$this->DefaultView(),$this->par['viewHtml'],$this->par['outerHtml']); if ($this->par['generate_view']) { echo "
View template:"; echo "
";
      echo  $this->defaultViewTemplate(1);
      echo "

"; } } ############################################################################ //! process 'list' screen function processList($post /*!< usually $_REQUEST */) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: processList (",$post,")
"; } $this->process_name = 'list'; $this->process_autovars(); if ($this->on_start) { $func = $this->on_start; $r = $func($this,$post); } if ($post['do_filter'] and $this->on_filter) { $this->reset('nosort'); $func = $this->on_filter; $r = $func($this,$post); if ($r) { $this->save_filter($post); } } $this->expose_filter(); $this->page_requested = $post['page']; if (isset($post['sort'])) { $this->sort = $post['sort']; } ###$this->getListCount(); $this->readListAll(1); $_VARS['url']=$this->original_url; ##todo $_VARS['original_url']=$this->original_url; #if ($this->original_query) $_VARS['original_url'] .= "?{$this->original_query}"; $_VARS['original_url'] = append_url($_VARS['original_url'],$this->original_query); if (!$this->list_post) $this->list_post = array(); if ($post) { foreach (array_keys($post) as $f) { if ($this->par['debug']) echo "saving $f => {$post[$f]}" . '
'; $this->list_post[$f] = $post[$f]; } } $_VARS['post'] = $this->list_post; ##todo $_VARS['mode']='list'; $_VARS['res']=$this->listRes; $_VARS['resCount']=$this->listCount; $_VARS['resFirst']= $this->listCount ? ($this->page*$this->par['pagesize'] + 1) : 0; $_VARS['resLast']= $this->listCount ? ($_VARS['resFirst'] + count($this->listRes) - 1) : 0; $_VARS['pageLinks']=$this->makePageLinks(); $_VARS['pager']=$this->defaultOrCustomPager(); $_VARS['cantadd'] = null; $_VARS['cantdel'] = null; if ($this->readonly) { $_VARS['readonly'] = 'readonly'; $_VARS['cantadd'] = 1; $_VARS['cantdel'] = 1; } else { $_VARS['readonly'] = null; } if ($this->cantadd) $_VARS['cantadd'] = 1; if ($this->cantdel) $_VARS['cantdel'] = 1; foreach ($this->par['listFields'] as $f) { $f = $this->getBareFieldName($f); #$_VARS['sort'][$f]['url'] = "{$_VARS['url']}?sort=$f"; $_VARS['sort'][$f]['url'] = append_url($_VARS['url'],"sort=$f"); if ($this->sort==$f) { $_VARS['sort'][$f]['sym'] = $this->sortUpInd; #$_VARS['sort'][$f]['url'] = "{$_VARS['url']}?sort=$f-"; $_VARS['sort'][$f]['url'] = append_url($_VARS['url'],"sort=$f-"); } else if ($this->sort=="$f-") $_VARS['sort'][$f]['sym'] = $this->sortDnInd; else $_VARS['sort'][$f]['sym'] = $this->noSortInd; } if ($this->on_render) { $func = $this->on_render; $r = $func($this,$post); if (! $r) return; } $this->showHtmlPageWithContent($this->par['listHtml']?'':$this->defaultList(),$this->par['listHtml'],$this->par['outerHtml']); ## todo if ($this->par['generate_list']) { echo "
List template:"; echo "
";
      echo $this->defaultListTemplate(1);
      echo "

"; } if ($this->par['generate_pager']) { echo "
Pager template:"; echo "
";
      echo $this->defaultPagerTemplate(1);
      echo "

"; } } ############################################################################ //! \private function save_filter($post) { if ($this->par['debug']>=5) { echo "Call: save_filter (",$post,")
"; } $this->filter_data = array(); foreach(array_keys($post) as $k) { if (preg_match('/^filter_/',$k)) { //pdebug("$k -> {$post[$k]}"); $this->filter_data[$k] = $post[$k]; } } } ############################################################################ //! \private function expose_filter() { if ($this->par['debug']>=5) { echo "Call: expose_filter()
"; } global $_VARS; if ($this->filter_data) { foreach(array_keys($this->filter_data) as $k) { $_VARS[$k] = htmlspecialchars($this->filter_data[$k]); } } } ############################################################################ //! \private function readListAll($esc=0) { if ($this->par['debug']>=5) { echo "Call: readListAll
"; } $r = null; $count = null; $res = null; if ($this->on_read_list_all) { $func = $this->on_read_list_all; $r = $func($this,$count,$res); } else if ($this->onReadListAll) { $func = $this->onReadListAll; $r = $func($this,$count,$res); /* * return from onReadListAll: * $r=null - nothing processed * $r=0 - processed, but post-process needed ('for' below) * $r=1 - nothing more needed * * but $count=null or $res=null mean we need to recalculate */ } $this->listCount = ( (isset($r) and isset($count)) ? $count : $this->getListCount() ); $this->listRes = ( (isset($r) and isset($res)) ? $res : db_getAll($this->getListSelect()) ); if ($r) return; for ($i=0; $ilistRes);++$i) { foreach (array_keys($this->listRes[$i]) as $f) { $this->readFieldProcess('list',$f,$this->listRes[$i][$f]); } if ($this->on_read_list_row) { $func = $this->on_read_list_row; $func($this,$i,$this->listRes[$i]); } else if ($this->onReadListRow) { $func = $this->onReadListRow; $func($i,$this->listRes[$i]); } if ($esc) { if (gettype($this->listRes[$i][$f])=='string') $this->listRes[$i][$f] = htmlspecialchars($this->listRes[$i][$f]); } } } ############################################################################ //! \private function getListCount() { if ($this->par['debug']>=5) { echo "Call: getListCount
"; } ##: onGetListCount if ($this->on_get_list_count) { $func = $this->on_get_list_count; $r = $func($this); if (isset($r)) { return $r; } } else if ($this->onGetListCount) { $func = $this->onGetListCount; $r = $func($this); if (isset($r)) { return $r; } } if ($this->listCountSql) $s = $this->listCountSql; else { if ($this->listDistinct) { $s = "SELECT COUNT( distinct {$this->pk} ) FROM " . $this->getListCountTable(); } else { $s = "SELECT COUNT( * ) FROM " . $this->getListCountTable(); } $s .= $this->getWhere(); } if ($this->par['debug']) echo $s; $listCount = db_getOne($s); if ($this->par['limit'] and $listCount>$this->par['limit']) $listCount = $this->par['limit']; if ($this->par['debug']) echo ' => ' . $listCount . '
'; return $listCount; } ############################################################################ //! \private function getListCountTable() { if ($this->par['debug']>=5) { echo "Call: getListCountTable
"; } if ($this->par['listCountTable']) return $this->par['listCountTable']; if ($this->par['listTable']) return $this->par['listTable']; if ($this->par['table']) return $this->par['table']; return ''; } ############################################################################ //! \private function getListSelect() { if ($this->par['debug']>=5) { echo "Call: getListSelect
"; } $pk_included = 0; $s = "SELECT "; if ($this->listDistinct) { $s .= ' DISTINCT '; } foreach ($this->par['listFields'] as $f) { if ($this->par['fieldOptions'][$f]['Encrypt'] and $this->on_get_encryption_key) { $func = $this->on_get_encryption_key; $key = db_escapeSimple($func($this)); if ($key) { $f = "decode($f,'$key') $f"; } } $s .= "$f,"; if ($this->getBareFieldName($f)==$this->pk) $pk_included = 1; } if (!$pk_included) $s .= "{$this->pk},"; $s = rtrim($s,','); $s .= " FROM " . $this->getListTable(); $s .= $this->getWhere('list'); $s .= $this->getGroupBy(); $s .= $this->getHaving(); $s .= $this->getOrderBy(); if (isset($this->page_requested)) { $this->page = $this->page_requested; } else { if ($s != $this->lastListSql) { $this->page = 0; if ($this->par['debug']) echo 'Reset page as SQL chanded
'; } } $this->lastListSql = $s; if ($this->par['pagesize'] or $this->par['limit']) { $start = $this->par['pagesize'] * $this->page; $limit = ($this->par['pagesize']?$this->par['pagesize']:$this->par['limit']); if ($this->par['limit'] and ($start+$limit > $this->par['limit'])) $limit = $this->par['limit'] - $start; $s .= " LIMIT $start,$limit"; // $s .= " LIMIT $start,{$this->par['pagesize']}"; } if ($this->par['debug']) echo $s . '
'; return $s; } ############################################################################ //! \private function getPK() { if ($this->par['debug']>=5) { echo "Call: getPK
"; } foreach ($this->par['fields'] as $ff) { $f = $this->getBareFieldName($ff); if ($this->par['fieldOptions'][$f]['PK']) { if ($this->par['debug']) echo "PK: $f
"; return $f; } } return ''; } ############################################################################ //! \private function getListTable() { if ($this->par['debug']>=5) { echo "Call: getListTable
"; } if ($this->par['listTable']) return $this->par['listTable']; if ($this->par['table']) return $this->par['table']; return ''; } ############################################################################ //! \private function getWhere($list=null) { if ($this->par['debug']>=5) { echo "Call: getWhere($list)
"; } $w=array(); if ($list & $this->par['listWhere']) array_push($w,$this->par['listWhere']); else { if ($this->par['where']) array_push($w,$this->par['where']); } if ($this->where) array_push($w,$this->where); if ($this->where_and_array) $w = array_merge($w,$this->where_and_array); $w = join(' AND ',$w); if ($w) $w = " WHERE $w "; if ($this->par['debug']) echo $w . '
'; return $w; } ############################################################################ //! adds where subclause (to be AND'ed) function andWhere($s /*!< where subclause (e.g. name='john') */,$reset=0 /*!< 1 - reset where buffer */) { if (!$this->where_and_array || $reset) $this->where_and_array = array(); array_push($this->where_and_array,$s); } ############################################################################ //! 'smartly' adds where subclause (to be AND'ed) function andWhereSmartEqual($f /*!< field name */ ,$v /*!< value to match (may contain wildcards * and ?) */ ) { if (isset($v) && $v!='') { $v = preg_replace('/\*/','%',$v); $v = preg_replace('/\?/','_',$v); $v = db_escapeSimple($v); if (preg_match('/[%_]/',$v)) $this->andWhere("$f like '$v'"); else $this->andWhere("$f='$v'"); } } ############################################################################ //! resets where buffer (for andWhere and andWhereSmartEqual) function andWhereReset() { $this->where_and_array = null; } ############################################################################ //! resets where, groupby, having, orderby buffers and sort column function reset($opt=null /*!< ='nosort' - do not resert sort column */ ) { $this->where_and_array = null; $this->where = null; $this->groupby = null; $this->having = null; $this->orderby = null; $this->orderby2 = null; if ($opt!='nosort') $this->sort = $this->par['sort']; $this->page=0; $this->list_post = null; } ############################################################################ //! \private function getGroupBy() { if ($this->par['debug']>=5) { echo "Call: getGroupBy
"; } $w=array(); if ($this->par['groupby']) array_push($w,$this->par['groupby']); if ($this->groupby) array_push($w,$this->groupby); $w = join(',',$w); if ($w) $w = " GROUP BY $w "; if ($this->par['debug']) echo $w . '
'; return $w; } ############################################################################ //! \private function getHaving() { if ($this->par['debug']>=5) { echo "Call: getHaving
"; } $w=array(); if ($this->par['having']) array_push($w,$this->par['having']); if ($this->having) array_push($w,$this->having); $w = join(' AND ',$w); if ($w) $w = " HAVING $w "; if ($this->par['debug']) echo $w . '
'; return $w; } ############################################################################ //! \private function getOrderBy() { if ($this->par['debug']>=5) { echo "Call: getOrderBy
"; } $w=array(); if ($this->par['orderby']) array_push($w,$this->par['orderby']); if ($this->orderby) array_push($w,$this->orderby); if ($this->sort) array_push($w, preg_replace('/\-$/',' desc',$this->sort) ); if ($this->par['orderby2']) array_push($w,$this->par['orderby2']); if ($this->orderby2) array_push($w,$this->orderby2); $w = join(',',$w); if ($w) $w = " ORDER BY $w "; if ($this->par['debug']) echo $w . '
'; return $w; } ############################################################################ //! \private function readRecord($id=null,$esc=0,$why=null) { if ($this->par['debug']>=5) { echo "Call: readRecord ($id,$esc)
"; } if (!isset($id) || id=='') return; $sql = $this->getRecordSelect($id); if ($this->par['debug']) echo $sql . '
'; $r = db_getRow($sql); if ($r===false) { $this->recordRes = null; return; } foreach (array_keys($r) as $f) { $this->readFieldProcess('edit',$f,$r[$f]); if ($this->par['fieldOptions'][$f]['Format']=='upload' and $r[$f]!='') { $r["name.$f"] = $r[$f]; $r["path.$f"] = "{$this->upload_dir}/{$r[$this->pk]}/{$r[$f]}"; if ($why=='clone') $r["$f"] = $r["path.$f"]; // will use this to copy file } } $ret = 1; if ($this->on_read) { $func = $this->on_read; $ret = $func($this,$r,'db'.$why); } else if ($this->onRead) { $func = $this->onRead; $ret = $func($r,'db'.$why); } if ($esc and $ret) { foreach (array_keys($r) as $f) { if (gettype($r[$f])=='string') $r[$f] = htmlspecialchars($r[$f]); } } $this->recordRes = $r; } ############################################################################ //! \private function getRecordSelect($id) { $s = 'SELECT '; foreach ($this->par['fields'] as $f) { if ($this->par['fieldOptions'][$f]['Encrypt'] and $this->on_get_encryption_key) { $func = $this->on_get_encryption_key; $key = db_escapeSimple($func($this)); if ($key) { $f = "decode($f,'$key') $f"; } } $s .= "$f,"; } $s = rtrim($s,','); $s .= " FROM {$this->par['table']}"; if ($id) { $id = db_escapeSimple($id); $s .= " WHERE {$this->pk}='$id'"; } return $s; } ############################################################################ //! \private function initRecord($esc=0) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: initRecord ($esc)
"; } $r = array(); foreach ($this->par['fields'] as $f) { if (isset($this->par['fieldOptions'][$f]['Default'])) { $r[$f] = $this->par['fieldOptions'][$f]['Default']; if (preg_match('/^\?=/',$r[$f])) { $r[$f] = eval_string('<'.$r[$f].'?'.'>'); } } if ($this->par['debug']>=5) echo "init: " .$f .'=>'.$r[$f].'
'; } if ($this->on_init_record) { $func = $this->on_init_record; $func($this,$r); } else if ($this->onInitRecord) { $func = $this->onInitRecord; $func($r); } if ($this->on_read) { $func = $this->on_read; $func($this,$r,'init'); } else if ($this->onRead) { $func = $this->onRead; $func($r,'init'); } if ($esc) { foreach (array_keys($r) as $f) { if (gettype($r[$f])=='string') $r[$f] = htmlspecialchars($r[$f]); } } if ($this->par['debug']>=10) { echo "initRecord res:
"; print_r ($r); } return $r; } ############################################################################ //! \private function deleteRecord($id) { if ($this->par['debug']>=5) { echo "Call: deleteRecord($id)
"; } $r = 1; $this->errors = array(); if ($this->readonly || $this->cantdel) { array_push($this->errors,'Table in read only node'); return 0; } if ($this->on_delete) { $func = $this->on_delete; $r = $func($this,$id,$this->errors); } else if ($this->onDelete) { $func = $this->onDelete; $r = $func($id,$this->errors); } if (isset($id) && $id!='' && $r) { $sql = $this->delete($id); if ($this->par['debug']) echo $sql. '
'; db_query($sql); if (is_dir("{$this->upload_dir}/$id")) rmdir_r("{$this->upload_dir}/$id"); if ($this->on_after_delete) { $func = $this->on_after_delete; $func($this,$id); } else if ($this->onAfterDelete) { $func = $this->onAfterDelete; $func($id); } } return $r; } ############################################################################ //! \private function defaultListTemplate($html=0) { $s=''; $ncol=count($this->par['listFields']); #--------------------------------------------------------------------------- # Table Header #--------------------------------------------------------------------------- $s.=<< EOD; #--------------------------------------------------------------------------- foreach ($this->par['listFields'] as $f) { $f = $this->getBareFieldName($f); $fn = $this->par['fieldOptions'][$f]['Caption']; if (!$fn) $fn=$f; #--------------------------------------------------------------------------- $s.=<< <@=@_VARS['sort']['$f']['sym']@>$fn  EOD; #--------------------------------------------------------------------------- } # /foreach ($this->par['listFields'] as $f) #--------------------------------------------------------------------------- $s.=<< Refresh  EOD; #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # Table Body #--------------------------------------------------------------------------- $s.=<<
EOD; #--------------------------------------------------------------------------- $firstfld = ''; foreach ($this->par['listFields'] as $f) { $f = $this->getBareFieldName($f); if (!$firstfld) $firstfld = $f; #--------------------------------------------------------------------------- $s.=<< <@=@r['$f']@>  EOD; #--------------------------------------------------------------------------- } # /foreach ($this->par['listFields'] as $f) #--------------------------------------------------------------------------- $s.=<< <@ if (!@_VARS['readonly']) { @> <@ if ( ! @_VARS['cantadd'] ) { @> <@ } @> <@ if ( ! @_VARS['cantdel'] ) { @> <@ } @> <@ } @> <@ ++@i; }@> EOD; #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- # Table Footer #--------------------------------------------------------------------------- $s.=<<
 <@=@_VARS['resFirst']@> - <@=@_VARS['resLast']@> (<@=@_VARS['resCount']@>)  <@ if (!@_VARS['readonly']) { @> <@ if ( ! @_VARS['cantadd'] ) { @> <@ } @> <@ } @>  
 <@=@_VARS['pager']@>   
EOD; #--------------------------------------------------------------------------- $s = preg_replace('/<@/','',$s); $s = preg_replace('/@>/','?>',$s); $s = preg_replace('/@/','$',$s); if ($html) { $s = preg_replace('/\&/','&',$s); $s = preg_replace('//','>',$s); } return $s; } ############################################################################ //! \private function defaultPagerTemplate($html=0) { $s=''; #--------------------------------------------------------------------------- # Pagelinks #--------------------------------------------------------------------------- $s.=<< <@ if (!@_VARS['pageLinks'][0]['first']) { @>">|<<@ @> <@ @>"><<@ } else { @>|< <<@ } @> <@ foreach (@_VARS['pageLinks'] as @r) { if (@r['current']) { @><@=@r['page1']@><@ } else { @>"><@=@r['page1']@><@ } @> <@ } if (!@_VARS['pageLinks'][0]['last']) { @>">><@ @> <@ @>">>|<@ } else { @>> >|<@ } @> <@ } @> EOD; #--------------------------------------------------------------------------- $s = preg_replace('/<@/','',$s); $s = preg_replace('/@>/','?>',$s); $s = preg_replace('/@/','$',$s); if ($html) { $s = preg_replace('/\&/','&',$s); $s = preg_replace('//','>',$s); } return $s; } ############################################################################ //! \private function defaultList() { global $_VARS; return eval_string($this->defaultListTemplate()); } ############################################################################ //! \private function defaultOrCustomPager() { global $_VARS; return eval_string( $this->par['pagerHtml'] ? _getpage($this->par['pagerHtml'],$this->onGetPage) : $this->defaultPagerTemplate() ); } ############################################################################ //! \private function defaultEditTemplate($html=0) { $enctype=''; $s = ''; $i = 0; foreach ($this->par['fields'] as $f) { $fn = $this->par['fieldOptions'][$f]['Caption']; if (!$fn) $fn=$f; $maxlength = ''; if ($f==$this->pk) { if ( preg_match ('/(int)|(num)/', $this->par['fieldOptions'][$f]['Type']) ) { #--------------------------------------------------------------------------- $s.=<<$fn<@=@_VARS['res']['$f']@>  EOD; #--------------------------------------------------------------------------- } else { $maxlength = $this->par['fieldOptions'][$f]['Len']; $maxlength = "maxlength='$maxlength'"; #--------------------------------------------------------------------------- $s.=<< <@ if ( @_VARS['is_new']) { @> * $fn <@ } else { @> $fn <@=@_VARS['res']['$f']@>  <@ } @> EOD; #--------------------------------------------------------------------------- } } else { $rows = $this->par['fieldOptions'][$f]['Rows']; $cols = $this->par['fieldOptions'][$f]['Cols']; if (!isset($rows) && !isset($cols) && ($this->par['fieldOptions'][$f]['Type']=='text' || $this->par['fieldOptions'][$f]['Type']=='blob')) { $rows = 5; } if (! $this->par['fieldOptions'][$f]['Null']) $mandatorymark = '* '; else $mandatorymark = ''; if ( preg_match ('/(string)|(varchar)|(char)/', $this->par['fieldOptions'][$f]['Type']) && $this->par['fieldOptions'][$f]['Len'] ) $maxlength = $this->par['fieldOptions'][$f]['Len']; $maxlength = "maxlength='$maxlength'"; if (preg_match('/hidden/',$this->par['fieldOptions'][$f]['Format'])) { #--------------------------------------------------------------------------- $s.=<< EOD; #--------------------------------------------------------------------------- } else if (preg_match('/upload/',$this->par['fieldOptions'][$f]['Format'])) { $enctype=' enctype="multipart/form-data"'; #--------------------------------------------------------------------------- $s.=<<$mandatorymark$fn <@ if (@_VARS['res']['$f']) { @> <@=@_VARS['res']['name.$f']@> Delete
<@ } @> type=file name="dbfile_$f"> EOD; #--------------------------------------------------------------------------- } else if ($rows>1) { if ($cols) $size="cols=$cols rows=$rows"; else $size="rows=$rows"; #--------------------------------------------------------------------------- $s.=<<$mandatorymark$fn EOD; #--------------------------------------------------------------------------- } else { if ($cols) $size="size=$cols"; else $size=""; #--------------------------------------------------------------------------- $s.=<<$mandatorymark$fn $maxlength type=text name="db_$f" value="<@=@_VARS['res']['$f']@>" $size> EOD; #--------------------------------------------------------------------------- } } ++$i; } #--------------------------------------------------------------------------- $s.=<< <@ if ( @_VARS['res'] !== null ) { @> <@ if ( ! @_VARS['readonly'] ) { @> <@ } @> <@ if (! @_VARS['is_new']) { @> <@ if ( ! @_VARS['cantadd'] ) { @> <@ } @> <@ if ( ! @_VARS['readonly'] ) { @> <@ if ( ! @_VARS['cantdel'] ) { @> <@ } @> <@ } @> <@ } @> <@ } else { @> <@ if ( ! @_VARS['cantadd'] ) { @> <@ } @> <@ } @> EOD; #--------------------------------------------------------------------------- #--------------------------------------------------------------------------- $s1=<<<@=@_VARS['errors']@><@ } @>
<@ if ( @_VARS['res'] !== null ) { @> EOD; #--------------------------------------------------------------------------- $s = $s1 . $s; $s = preg_replace('/<@/','',$s); $s = preg_replace('/@>/','?>',$s); $s = preg_replace('/@/','$',$s); if ($html) { $s = preg_replace('/\&/','&',$s); $s = preg_replace('//','>',$s); } return $s; } ############################################################################ //! \private function defaultEdit() { global $_VARS; return eval_string($this->defaultEditTemplate()); } ############################################################################ //! \private function showErrorPage($errors,$url=null) { if ($this->par['errorHtml']) $this->showHtmlPageWithContent(join('
',$errors),$this->par['errorHtml'],$this->par['outerHtml']); else { $text = "".join('
',$errors) . "


Continue"; $this->showHtmlPageWithContent($text,'',$this->par['outerHtml']); } } ############################################################################ ############################################################################ //! \private function defaultViewTemplate($html=0) { #--------------------------------------------------------------------------- $s=<<<@=@_VARS['errors']@><@ } @>
<@ if ( @_VARS['res']) { @> EOD; #--------------------------------------------------------------------------- $i = 0; foreach ($this->par['fields'] as $f) { $fn = $this->par['fieldOptions'][$f]['Caption']; if (!$fn) $fn=$f; #--------------------------------------------------------------------------- $s.=<< EOD; #--------------------------------------------------------------------------- ++$i; } #--------------------------------------------------------------------------- $s.=<<
$fn <@=@_VARS['res']['$f']@> 
Exit
EOD; #--------------------------------------------------------------------------- $s = preg_replace('/<@/','',$s); $s = preg_replace('/@>/','?>',$s); $s = preg_replace('/@/','$',$s); if ($html) { $s = preg_replace('/\&/','&',$s); $s = preg_replace('//','>',$s); } return $s; } ############################################################################ //! \private function defaultView() { global $_VARS; return eval_string($this->defaultViewTemplate()); } ############################################################################ ############################################################################ //! \private function insert($post) { $s = "INSERT INTO {$this->par['table']} ("; foreach ($this->par['fields'] as $f) { $s .= "$f,"; } $s = rtrim($s,','); $s .= ') VALUES ('; foreach ($this->par['fields'] as $f) { if ($this->par['fieldOptions'][$f]['Format'] == 'upload') { if ($post["dbfiledel_$f"]) { $s .= "null,"; } else if ($_FILES["dbfile_$f"]['size']) { $v = db_escapeSimple($_FILES["dbfile_$f"]['name']); $s .= "'$v',"; } else if (isset($post["dbfileold_$f"])) { $v = db_escapeSimple(basename($post["dbfileold_$f"])); $s .= "'$v',"; $this->upload = 1; } else { //$s .= "default,"; $s .= "null,"; } } else if (isset($post["db_$f"])) { $v = db_escapeSimple($post["db_$f"]); $v = "'$v'"; if ($this->par['fieldOptions'][$f]['Encrypt'] and $this->on_get_encryption_key) { $func = $this->on_get_encryption_key; $key = db_escapeSimple($func($this)); if ($key) { $v = "encode($v,'$key')"; } } $s .= "$v,"; } else { //$s .= "default,"; $s .= "null,"; } } $s = rtrim($s,','); $s .= ')'; return $s; } ############################################################################ //! \private function update($post) { $s = ''; foreach ($this->par['fields'] as $f) { if ($f!=$this->pk) { if ($this->par['fieldOptions'][$f]['Format'] == 'upload') { if ($post["dbfiledel_$f"]) { $s .= "$f=null,"; } else if ($_FILES["dbfile_$f"]['size']) { $v = db_escapeSimple($_FILES["dbfile_$f"]['name']); $s .= "$f='$v',"; } else if (isset($post["dbfileold_$f"])) { $v = db_escapeSimple($post["dbfileold_$f"]); $s .= "$f='$v',"; } } else if (isset($post["db_$f"])) { $v = db_escapeSimple($post["db_$f"]); $v = "'$v'"; if ($this->par['fieldOptions'][$f]['Encrypt'] and $this->on_get_encryption_key) { $func = $this->on_get_encryption_key; $key = db_escapeSimple($func($this)); if ($key) { $v = "encode($v,'$key')"; } } $s .= "$f=$v,"; } } } $s = rtrim($s,','); if ($s==='') return ''; $s = "UPDATE {$this->par['table']} set $s"; $id = db_escapeSimple($post['db_'.$this->pk]); $s .= " WHERE {$this->pk}='$id'"; return $s; } ############################################################################ //! \private function delete($id) { $id = db_escapeSimple($id); $s = "DELETE FROM {$this->par['table']} "; $s .= " WHERE {$this->pk}='$id'"; return $s; } ############################################################################ //! \private function readFieldProcess($when,$f,&$val) { if ($this->par['debug']>=8) { echo "Call: readFieldProcess ($when,$f,$val)
"; } $r=0; if ($this->on_read_field) { $func = $this->on_read_field; $r = $func($this,$when,$f,$val); } else if ($this->onReadField) { $func = $this->onReadField; $r = $func($when,$f,$val); } if (!$r) { if ( preg_match ('/^(date)|(datetime)\w/', $this->par['fieldOptions'][$f]['Type'] ) ) { #$fmt = preg_match('/mdy/i',$this->par['fieldOptions'][$f]['Format']) ? 'mdy' : 'dmy'; $fmt = $this->par['fieldOptions'][$f]['Format']; $val = Date2Human ( $val, $fmt ); } } } ############################################################################ //! \private function makePageLinks() { $qs = $this->original_query; $qs = preg_replace('/(^|\W)(page=\w*)(\W|$)/','$1$3',$qs); $qs = preg_replace('/&&/','&',$qs); $qs = preg_replace('/^&/','',$qs); $qs = preg_replace('/&$/','',$qs); $qs .= ($qs ? '&' : '') . 'pager=1'; $la = array(); if ($this->listCount && $this->par['pagesize'] && ($this->listCount>$this->par['pagesize'])) { $pc = ceil($this->listCount/$this->par['pagesize']); if ($pc > $this->pageLinksCount) { $p1 = $this->page - $this->pageLinksCount/2; if ($p1<0) $p1 = 0; $p2 = $p1 + $this->pageLinksCount; if ($p2>$pc) { $p2 = $pc+1; $p1=$p2 - $this->pageLinksCount; } } else { $p1 = 0; $p2 = $pc; } for ($i=0,$p=0; $i<$this->listCount && $p<$p2; $i += $this->par['pagesize'],++$p) { if ($p>=$p1) $la[$p] = array('page'=>$p,'page1'=>$p+1,'current'=>($p==$this->page),'qs'=>"&$qs"); } if ($this->page==0) { $la[0]['first'] = 1; } else { $la[0]['prevpage'] = $this->page-1; $la[0]['firstpage'] = 0; } if ($this->page==$pc-1) { $la[0]['last'] = $pc; } else { $la[0]['nextpage'] = $this->page+1; $la[0]['lastpage'] = $pc-1; } $la[0]['qs'] = "&$qs"; } return $la; } ############################################################################ //! \private function upload(&$post) { $first = 1; $uploaddir = "{$this->upload_dir}/{$post['db_'.$this->pk]}"; foreach ($this->par['fields'] as $f) { $oldfile = $post["dbfileold_$f"]; $file = "dbfile_$f"; if ($oldfile!='' and $post["dbfiledel_$f"]) { if (is_file("$uploaddir/$oldfile")) unlink("$uploaddir/$oldfile"); } else if ($post['is_new'] and $oldfile!='' and !$_FILES[$file]['size']) { if ($first) { mkdir_r($uploaddir); $first = 0; } $copyfile = basename($oldfile); copy($oldfile,"$uploaddir/$copyfile"); } if ($_FILES[$file]['size']) { if (is_file("$uploaddir/$oldfile")) unlink("$uploaddir/$oldfile"); if ($first) { mkdir_r($uploaddir); $first = 0; } $uploadfile = $_FILES[$file]['name']; $uploadfile = "$uploaddir/$uploadfile"; if (! move_uploaded_file($_FILES[$file]['tmp_name'], $uploadfile)) { # ?? #$_VARS['err'] .= '
' . $_FILES[$f1]['error']; #return 0; } } } } ############################################################################ //! \private function save(&$post) { if ($this->par['debug']>=5) { echo "Call: save (",$post,")
"; } if ($this->readonly) { array_push($this->errors,'Table in read only node'); return 0; } if ($post['is_new'] && $this->cantadd) { array_push($this->errors,'Can not add to this table'); return 0; } $r = 1; if ($this->on_save) { $func = $this->on_save; $r = $func($this,$post); } else if ($this->onSave) { $func = $this->onSave; $r = $func($post); } if (!$r) return 0; /* foreach ($this->par['fields'] as $f) { if (isset($post["db_$f"])) { $r=0; if ($this->onSaveField) { $func = $this->onSaveField; $r = $func($f,$post["db_$f"]); } if (!$r) { if (preg_match ('/^(date)|(datetime)\w/', $this->par['fieldOptions'][$f]['Type'] )) { $fmt = preg_match('/mdy/i',$this->par['fieldOptions'][$f]['Format']) ? 'mdy' : 'dmy'; $post["db_$f"] = Date2Comp ( $post["db_$f"], $fmt ); } } } } */ if ($post['is_new'] || !$post['db_'.$this->pk]) { if (!$post['db_'.$this->pk]) $post['db_'.$this->pk] = db_nextId($this->par['table']); $s = $this->insert($post); } else { $s = $this->update($post); } if ($this->par['debug']) echo $s. '
'; if ($s !== '') { db_query($s,false); if ($err=db_error()) { $r=1; if ($this->on_dberr) { $func = $this->on_dberr; $r = $func($this,'save',db_errno(),$err); } if ($r) array_push($this->errors,$err); return 0; } } if ($this->upload) $this->upload($post); if ($this->on_after_save) { $func = $this->on_after_save; $r = $func($this,$post); } else if ($this->onAfterSave) { $func = $this->onAfterSave; $r = $func($post); } return 1; } ############################################################################ //! \private function getErrorText($err,$fld,$par=null) { $ERRORS['en']['mandatory'] = "'%s' is a mandatory field"; $ERRORS['en']['int'] = "'%s' must be an integer"; $ERRORS['en']['number'] = "'%s' must be a number"; $ERRORS['en']['date'] = "'%s' is not a valid date"; $ERRORS['en']['len'] = "'%s' is to long (%d symbols allowed)"; $ERRORS['en']['pk'] = "'%s' has duplicated value"; $ERRORS['en']['upload'] = "Error uploading file '%s'"; $ERRORS['ru']['mandatory'] = "Поле '%s' должно быть задано"; $ERRORS['ru']['int'] = "Поле '%s' должно быть целым числом"; $ERRORS['ru']['number'] = "Поле '%s' должно быть числом"; $ERRORS['ru']['date'] = "Поле '%s' - неверная дата"; $ERRORS['ru']['len'] = "Поле '%s' - слишком длинное значение (больше %d)"; $ERRORS['ru']['pk'] = "Поле '%s' не уникально"; $ERRORS['ru']['upload'] = "Ошибка загрузки файла '%s'"; $f = $this->fieldOptions[$fld]['Caption']; if (!$f) $f = $fld; return sprintf($ERRORS[$this->lang][$err],$f,$par); } ############################################################################ //! \private function validate($post) { global $_VARS; if ($this->par['debug']>=5) { echo "Call: validate (",$post,")
"; } #$goodpost = array(); #$goodpost['is_new'] = $post['is_new']; $goodpost = $post; $this->upload = 0; $r = 1; unset($this->errors); $this->errors = array(); if ($this->readonly) { array_push($this->errors,'Table in read only node'); return 0; } if ($this->edit_readonly && !$goodpost['is_new']) { array_push($this->errors,'Record in read only node'); return 0; } foreach ($this->par['fields'] as $f) { if ($this->par['debug']>=5) { echo "Call: validating (",$f,")
"; } $fn = $this->par['fieldOptions'][$f]['Caption']; if (!$fn) $fn=$f; if (isset($post["db_$f"])) { $goodpost["db_$f"]=ltrim(rtrim($post["db_$f"])); } else if ($goodpost['is_new'] and isset($this->par['fieldOptions'][$f]['Default'])) { $goodpost["db_$f"]=$this->par['fieldOptions'][$f]['Default']; #### nb } $vfr=1; if ($this->on_validate_field) { $func = $this->on_validate_field; $vfr = $func($this,$f,$goodpost["db_$f"],$this->errors); //returns: 0 - bad value // 1 - ok, standard validation needed // 2 - ok, do not validate more } if ($vfr==0) $r = 0; // not validated if ($vfr==1 and $goodpost["db_$f"] !== null) { if ( (!($this->par['fieldOptions'][$f]['Null']) && ($goodpost["db_$f"]==='')) && !($goodpost['is_new'] && $f==$this->pk && preg_match ('/(int)|(num)/', $this->par['fieldOptions'][$f]['Type'])) ) { array_push($this->errors,$this->getErrorText('mandatory',$fn)); $r = 0; } if ( preg_match ('/int/', $this->par['fieldOptions'][$f]['Type']) && ! preg_match('/^\d*$/',$goodpost["db_$f"])) { array_push($this->errors,$this->getErrorText('int',$fn)); $r = 0; } if ( preg_match ('/^num/', $this->par['fieldOptions'][$f]['Type']) && ! preg_match('/^\d*\.?\d*$/',$goodpost["db_$f"])) { array_push($this->errors,$this->getErrorText('number',$fn)); $r = 0; } if (isset($goodpost["db_$f"]) && ($goodpost["db_$f"]!='') && preg_match ('/^(date)|(datetime)\w/', $this->par['fieldOptions'][$f]['Type'] ) ) { $fmt = preg_match('/mdy/i',$this->par['fieldOptions'][$f]['Format']) ? 'mdy' : 'dmy'; $dt1 = Date2Comp($goodpost["db_$f"],$fmt); if (substr($dt1,0,10)=='0000-00-00') continue; # null time $dt2 = strftime('%Y-%m-%d %H:%M:%S',strtotime($dt1)); if ($dt1!=$dt2) { array_push($this->errors,$this->getErrorText('date',$fn)); $r = 0; } else { $goodpost["db_$f"]=$dt1; } } if ( preg_match ('/(string)|(varchar)|(char)/', $this->par['fieldOptions'][$f]['Type']) && $this->par['fieldOptions'][$f]['Len'] ) { if (strlen($goodpost["db_$f"]) > $this->par['fieldOptions'][$f]['Len']) { array_push($this->errors,$this->getErrorText('len',$fn,$this->par['fieldOptions'][$f]['Len'])); $r = 0; } } } if ($_FILES["dbfile_$f"]['name']) { if (!$_FILES["dbfile_$f"]['size']) { array_push($this->errors,$this->getErrorText('upload',$fn)); $r = 0; } else { $this->upload = 1; } } } if ($goodpost['is_new'] and $goodpost["db_{$this->pk}"]!='') { // pdebug("gonna check {$this->pk} on table {$this->par['table']}"); $pkval = db_escapeSimple ($goodpost["db_{$this->pk}"]); $exists = db_getOne("select {$this->pk} from {$this->par['table']} where {$this->pk}='$pkval'"); if (isset($exists)) { array_push ( $this->errors, $this->getErrorText('pk',$fn,htmlspecialchars($goodpost["db_{$this->pk}"])) ); $r = 0; } } $ur = 1; if ($this->on_validate) { $func = $this->on_validate; $ur = $func($this,$goodpost,$this->errors); } else if ($this->onValidate) { $func = $this->onValidate; $ur = $func($goodpost,$this->errors); } if ($r && $ur) return $goodpost; return 0; } ############################################################################ //! \private function readRecordFromPost(&$post,$esc=0) { #&& $r = array(); #foreach ($this->par['fields'] as $f) { # $r[$f] = $post["db_$f"]; #} foreach (array_keys($post) as $f) { if (preg_match('/^db_(.+)$/',$f,$a)) { $r[$a[1]] = $post[$f]; } else if (preg_match('/^dbfileold_(.+)$/',$f,$a)) { $r[$a[1]] = $post[$f]; } } if ($this->on_read) { $func = $this->on_read; $func($this,$r,'post'); } else if ($this->onRead) { $func = $this->onRead; $func($r,'post'); } if ($esc) { foreach (array_keys($r) as $f) { if (gettype($r[$f])=='string') $r[$f] = htmlspecialchars($r[$f]); } } return $r; } ############################################################################ //! \private function getBareFieldName($f) { #$f = preg_replace('/^\w+\./','',$f); #$f = preg_replace('/^[\w().]+\s+/','',$f); $f = preg_replace('/^.+\s+/','',$f); $f = preg_replace('/^.+\./','',$f); return $f; } ############################################################################ //! \private function showHtmlPage($page='',$template=null) { _showpage('',$page,isset($template)?$template:$this->par['outerHtml'],$this->onGetPage); } ############################################################################ //! \private function showHtmlPageWithContent($content='',$page='',$template=null) { _showpage($content,$page,isset($template)?$template:$this->par['outerHtml'],$this->onGetPage); } } ############################################################################ # Non members ############################################################################ /****************************************************************************/ //! shows page in a template function _showpage($text='',$page='',$template='',$func='') { global $_VARS; global $CHARSET; $savetxt=$_VARS['text']; $savepage=$_VARS['_page']; if ($page) $_VARS['_page'] = $page; if ($text) $_VARS['text'] = $text; if ($page && ($txt=_getpage($page,$func))) $_VARS['text'] = $txt; if ($template && ($txt=_getpage($template,$func))) $_VARS['text'] = $txt; if (!headers_sent() and $CHARSET) { header("Content-Type: text/html; charset=$CHARSET",true); } echo $_VARS['text']; $_VARS['text']=$savetxt; $_VARS['_page']=$savepage; } /****************************************************************************/ //! gets a page function _getpage($page,$func='') { global $HTML_DIR, $_VARS; if ($page) { if ($func) { $res = $func($page); if ($res) { return $res; } } if (! preg_match('/\.html?$/',$page) ) { $page = "$page.htm"; } #$dir = $HTML_DIR; $dirs = split('\s*[;:]\s*',$HTML_DIR); foreach ($dirs as $dir) { if ($dir) $dir = "$dir/"; if (is_file("$dir$page")) { ob_start(); include ($dir.$page); $res = ob_get_contents(); ob_end_clean(); return $res; } } } return ''; } /****************************************************************************/ //! gets a template function _gettemplate($tpl) { global $HTML_DIR, $_VARS; if (! preg_match('/\.html?$/',$tpl) ) { $page = "$tpl.htm"; } #$dir = $HTML_DIR; $dirs = split('\s*[;:]\s*',$HTML_DIR); foreach ($dirs as $dir) { if ($dir) $dir = "$dir/"; if (is_file("$dir$tpl")) { $res = file_get_contents("$dir$tpl"); return $res; } } return ''; } /****************************************************************************/ //! renders html tag input type=text function input_text($n /*!< field name */,$v=null /*!< value */,$rest=null /*!< other field attributes */) { $s=<< EOD; return $s; } ############################################################################ //! renders html tag input type=hidden function input_hidden($n /*!< field name */,$v=null /*!< value */,$rest=null /*!< other field attributes */) { $s=<< EOD; return $s; } ############################################################################ //! renders html tag textarea function input_textarea($n /*!< field name */,$v=null /*!< value */,$rest=null /*!< other field attributes */) { $s=<<$v EOD; return $s; } ############################################################################ //! renders html tag input type=checkbox function input_checkbox($n /*!< field name */,$v=null /*!< real value */,$cv=null /*!< value attribute */,$rest=null /*!< other field attributes */) { $checked = ''; if ($v==$cv) $checked = 'checked'; $s=<< EOD; return $s; } ############################################################################ //! renders html tag input type=radio function input_radio($n /*!< field name */,$v=null /*!< real value */,$cv=null /*!< value attribute */,$rest=null /*!< other field attributes */) { $checked = ''; if ($v==$cv) $checked = 'checked'; $s=<< EOD; return $s; } ############################################################################ //! renders html tag select function input_select( $n /*!< field name */ ,$v /*!< value */ ,$select /*!< sql-statement returning 2 columns or array of 2-items arrays */ ,$rest=null /*!< other field attributes */ ,$pleaseselect=null /*!< empty option title to add to top */ ) { if (gettype($select)=='string') $list = db_getAll($select,array(),DB_FETCHMODE_ORDERED); elseif (gettype($select)=='array') $list = $select; $s=""; } ############################################################################ //! converts date from dd/mm/yyyy or mm/dd/yyyy [h:m] to yyyy-mm-dd [h:m] function Date2Comp($str,$fmt='dmy') { if (preg_match('/^\s*(\d+)\s*[\.\-\/]\s*(\d+)\s*[\.\-\/]\s*(\d+)(.*)$/',$str,$a)) { $day = sprintf('%02d',$fmt=='mdy' ? $a[2] : $a[1]); $mon = sprintf('%02d',$fmt=='mdy' ? $a[1] : $a[2]); if ($a[3]<100) $a[3]+=2000; $yer = sprintf('%04d',$a[3]); $hr = ltrim(rtrim($a[4])); list($hr,$mi,$sc) = split(':',$hr); $hr = sprintf('%02d:%02d:%02d',$hr,$mi,$sc); $str="$yer-$mon-$day $hr"; } return $str; } ############################################################################ //! converts date from yyyy-mm-dd [h:m] to dd/mm/yyyy or mm/dd/yyyy [h:m] function Date2Human($str,$fmt=null) { if (!$fmt) $fmt='dmy hm'; # default if (preg_match('/(\d+)[\.\-\/](\d+)[\.\-\/](\d+)(.*)$/',$str,$a)) { $yer = sprintf('%04d',$a[1]); $mon = sprintf('%02d',$a[2]); $day = sprintf('%02d',$a[3]); $hms = $a[4]; list($hr,$mi,$sc) = split(':',$hms); if (preg_match('/hms/',$fmt)) $hms = sprintf(' %02d:%02d:%02d',$hr,$mi,$sc); else if (preg_match('/hm/',$fmt)) $hms = sprintf(' %02d:%02d',$hr,$mi); else $hms = ''; if ($yer=='0000' && $mon='00' && $day=='00') return ''; $str = preg_match('/mdy/',$fmt) ? "$mon/$day/$yer$hms" : "$day/$mon/$yer$hms"; } return $str; } /****************************************************************************/ //! internal function ungraphic_submits() { foreach(array_keys($_POST) as $q) { if (preg_match('/_x$/',$q)) { $newq = substr($q,0,strlen($q)-2); if ($_POST[$newq.'_y']) { $_POST[substr($q,0,strlen($q)-2)] = $_POST[$q].'-'.$_POST[$newq.'_y']; $_REQUEST[substr($q,0,strlen($q)-2)] = $_POST[$q].'-'.$_POST[$newq.'_y']; } } } } ########################################################################### //! internal function unmagic_slashes() { set_magic_quotes_runtime(0); if (get_magic_quotes_gpc()) { function stripMagicSlashes($element) { if (is_array($element)) return array_map("stripMagicSlashes", $element); else return stripslashes($element); } // strip slashes fro all incoming GET/POST/COOKIE data. $_GET = array_map("stripMagicSlashes", $_GET); $_POST = array_map("stripMagicSlashes", $_POST); $_COOKIE = array_map("stripMagicSlashes", $_COOKIE); $_REQUEST = array_map("stripMagicSlashes", $_REQUEST); } } /****************************************************************************/ //! makes http redirect function redirect($url) { if (!headers_sent()) header("Location: $url"); else { echo<<Continue EOD; } } /****************************************************************************/ //! evals a string function eval_string($text) { global $_VARS; ob_start(); eval("?".chr(62).$text.chr(60)."?"); $return = ob_get_contents(); ob_end_clean(); return $return; } /****************************************************************************/ //! replaces " & ' to ` (for use in javascript) function jssafe($s) { $s = preg_replace("/'/",'`',$s); $s = preg_replace('/"/','`',$s); return $s; } /****************************************************************************/ //! internal function _do_hierarchical_query($parent=0,$lv=0,$hkey='') { global $_VARS; $res = db_getAll(eval("return \"{$_VARS['_hierarchical_sql']}\";")); foreach ($res as $r) { $r['_level'] = $lv; $r['_indent'] = str_repeat($_VARS['_hierarchical_indent'],$lv); $r['_hkey'] = $hkey . $r[$_VARS['_hierarchical_col']] . '#'; array_push($_VARS['_hierarchical_res'],$r); _do_hierarchical_query($r[$_VARS['_hierarchical_col']],$lv+1,$r['_hkey']); } } /****************************************************************************/ //! make hierarchical sql query function hierarchical_query($sql,$col,$start=0,$indent='') /* sql: 'select id,name,parentid from ay_client_cats where parentid=$parent order by id' - $parent should be present */ { global $_VARS; $save1 = $_VARS['_hierarchical_sql']; $save2 = $_VARS['_hierarchical_col']; $save3 = $_VARS['_hierarchical_res']; $save4 = $_VARS['_hierarchical_indent']; $_VARS['_hierarchical_sql'] = $sql; $_VARS['_hierarchical_col'] = $col; $_VARS['_hierarchical_res'] = array(); $_VARS['_hierarchical_indent'] = $indent; _do_hierarchical_query($start); $res = $_VARS['_hierarchical_res']; $_VARS['_hierarchical_sql'] = $save1; $_VARS['_hierarchical_col'] = $save2; $_VARS['_hierarchical_res'] = $save3; $_VARS['_hierarchical_indent'] = $save4; return $res; } ############################################################################ function mkdir_r($strPath, $mode = 0777) //creates directory tree recursively { #echo "
mkdir_r:$strPath"; return ($strPath=='/') or is_dir($strPath) or ( mkdir_r(dirname($strPath), $mode) and mkdir_rel($strPath, $mode) ); } ############################################################################ function mkdir_rel($strPath, $mode) { //creates dir relatively to script and chmod #echo "
mkdir_rel:$strPath"; if (preg_match('/^\//',$strPath)) { $strPath = "{$_SERVER['DOCUMENT_ROOT']}$strPath"; #echo "
mkdir_rel2:$strPath"; } $r = (is_dir($strPath) or mkdir($strPath, $mode)); if (!$r) return 0; if (!preg_match('/^\//',$strPath)) { $strPath = dirname($_SERVER['SCRIPT_FILENAME']) . "/$strPath"; } $r = chmod( $strPath,$mode ); #echo "
mkdir_rel-chmod:$f = $r"; return $r; } ############################################################################ function rmdir_r ($dir) { if (is_dir ($dir)) { if (cleardir ($dir)) { return rmdir ($dir); } return false; } return unlink ($dir); } ############################################################################ function cleardir ($dir) { if (!($dir = dir ($dir))) { return false; } while (false !== $item = $dir->read()) { if ($item != '.' && $item != '..' && !rmdir_r ($dir->path . DIRECTORY_SEPARATOR . $item)) { $dir->close(); return false; } } $dir->close(); return true; } ############################################################################ function append_url($url,$q=null) { if ($q===null) return $url; if (preg_match('/\?$/',$url)) return "$url$q"; if (preg_match('/&$/',$url)) return "$url$q"; if (preg_match('/\?/',$url)) return "$url&$q"; return "$url?$q"; } /****************************************************************************/ ungraphic_submits(); unmagic_slashes(); ?> php ############################################################################ # # Login related # ############################################################################ function CheckLogin($required=0,$nonautorizedurl=null,$outerhtml=null) { global $LOGIN_TABLEPREFIX; global $TABLEPREFIX; global $_VARS; global $_CMSITE_USER_RIGHTS; global $LOGIN_USE_COOKIES; global $LOGIN_EXPIRES; global $LOGIN_USE_IP; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; $_VARS['total_subscribers'] = db_getOne("select count(*) from {$tableprefix}logins"); $COOKIENAME = "{$tableprefix}simplelox"; if ($required) { $_VARS['_use_past_time_'] = 1; } if (! $LOGIN_USE_COOKIES) { session_start(); session_regenerate_id(1); $cookie = $_SESSION[$COOKIENAME]; } else { $cookie = $_COOKIE[$COOKIENAME]; } if ( $cookie ) { $tok = $_SERVER['HTTP_USER_AGENT']; if ($LOGIN_USE_IP) $tok .= $_SERVER['REMOTE_ADDR']; $tok = md5($tok); $where = "logged_id='$cookie$tok'"; $key = db_escapeSimple(get_my_secret_key()); if ($key) { $login_fld = "decode(login,'$key') login"; $rights_fld = "decode(rights,'$key') rights"; } else { $login_fld = "login"; $rights_fld = "rights"; } $res = db_getRow("select id,$login_fld,$rights_fld,accessed_dt,role_id,title,firstname,lastname from {$tableprefix}logins where $where"); $id = $res['id']; $login = $res['login']; $time1 = strtotime($res['accessed_dt']); if ($LOGIN_EXPIRES and (time()-$time1) > $LOGIN_EXPIRES*60) $id=0; if ($id) { db_query("update {$tableprefix}logins set accessed_dt=" . mysql_now() ." where id='$id'"); $cookieexpire = $LOGIN_EXPIRES? (time()+60*$LOGIN_EXPIRES) : null; if (! $LOGIN_USE_COOKIES) { session_start(); session_regenerate_id(1); $_SESSION[$COOKIENAME] = $cookie; } else { if (! setcookie($COOKIENAME,$cookie,null,'/')) echo "kuki not set 1"; if ($cookieexpire) { if (! setcookie($COOKIENAME,$cookie,$cookieexpire,'/')) echo "kuki not set 1a"; } } $_VARS['smauth_user_id'] = $id; $_VARS['smauth_login'] = $login; $_VARS['smauth_title'] = $res['title']; $_VARS['smauth_firstname'] = $res['firstname']; $_VARS['smauth_lastname'] = $res['lastname']; $_VARS['smauth_name'] = "{$res['title']} {$res['firstname']} {$res['lastname']}"; $_CMSITE_USER_RIGHTS = db_getOne("select rights from {$tableprefix}roles where id='{$res['role_id']}'"); $_VARS['smauth_user_rights'] = $_CMSITE_USER_RIGHTS; return $id; } } //pdebug($cookie); if ($required) { Login("{$_SERVER['PHP_SELF']}?{$_SERVER['QUERY_STRING']}",$nonautorizedurl,1,$outerhtml); exit; } else { unset($_VARS['smauth_user_id']); unset($_VARS['smauth_login']); unset($_VARS['smauth_title']); unset($_VARS['smauth_firstname']); unset($_VARS['smauth_lastname']); unset($_VARS['smauth_name']); return 0; } } ############################################################################ function GetUserRights($what,$ex=null) { global $_CMSITE_USER_RIGHTS; //pdebug($what); $a = array(); //if (preg_match("/^.*?\\s*$what\\((.*?)\\)\\s*.*\$/s",$_CMSITE_USER_RIGHTS,$a)) { if (preg_match("/<$what(\\s+(.*?))?\\s*\\/>/",$_CMSITE_USER_RIGHTS,$a)) { //pdebug('matched:'.htmlspecialchars("/<$what(\\s+(.*?))?\\s*\\/>/")); //pdebug('fullrights:'.htmlspecialchars($_CMSITE_USER_RIGHTS)); if (isset($ex)) { if ($ex == '*') return 1; if ($ex == '?') { return $a[2]; } else { $opt = $a[2]; if (preg_match("/(^|\\W)$ex=\"([^\"]*)\"/",$opt,$a)) { return $a[2]; } else { return '-'; } } return preg_match("/$ex/",$a[1]); } else return 1; } else return null; } ############################################################################ function Login ($autorizedurl=null,$nonautorizedurl=null,$show=null,$outer_html=null) ############################################################################ { global $LOGIN_TABLEPREFIX; global $TABLEPREFIX; global $LOGIN_USE_COOKIES; global $ON_AFTERLOGIN_PROC; global $LOGIN_USE_IP; global $LOGIN_EXPIRES; global $_VARS; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; $COOKIENAME = "{$tableprefix}simplelox"; if ($_POST['smauth_login_ok'] and $_POST['smauth_login']) { $login = db_escapeSimple($_POST['smauth_login']); $passwd = db_escapeSimple($_POST['smauth_passwd']); $key = db_escapeSimple(get_my_secret_key()); if ($key) { $login_fld = "decode(login,'$key')"; $passwd_fld = "decode(passwd,'$key') passwd"; } else { $login_fld = "login"; $passwd_fld = "passwd"; } $where = "$login_fld='$login'"; $res = db_getRow("select id,$passwd_fld from {$tableprefix}logins where $where"); $id = $res['id']; $cookieexpire = $LOGIN_EXPIRES? (time()+60*$LOGIN_EXPIRES) : null; if ($id and $res['passwd']==$passwd) // passwd is case snstv! { $logged_id = crypt($id . localtime() ) . $id; $tok = $_SERVER['HTTP_USER_AGENT']; if ($LOGIN_USE_IP) $tok .= $_SERVER['REMOTE_ADDR']; $tok = md5($tok); db_query("update {$tableprefix}logins set logged_id='$logged_id$tok',accessed_dt=" . mysql_now() ." where id='$id'"); if (! $LOGIN_USE_COOKIES) { session_start(); session_regenerate_id(1); $_SESSION[$COOKIENAME] = $logged_id; } else { if (! setcookie($COOKIENAME,$logged_id,null,'/') ) echo "kuki not set 2"; if ($cookieexpire) { setcookie($COOKIENAME,$logged_id,$cookieexpire,'/'); } } $_VARS['smauth_user_id'] = $id; $_VARS['smauth_login'] = $login; //pdebug('login:'.$_VARS['smauth_user_id']); if ($SMAUTH_AFTERLOGIN_PROC) { $SMAUTH_AFTERLOGIN_PROC(); } redirect($_POST['originalurl']); exit; } $_VARS['err'] = 'Login failed'; $_VARS['smauth_login'] = $login; } else if ($_POST['smauth_login_cancel']) { unset($_VARS['smauth_user_id']); unset($_VARS['smauth_login']); unset($_VARS['smauth_title'] ); unset($_VARS['smauth_firstname'] ); unset($_VARS['smauth_lastname'] ); unset($_VARS['smauth_name'] ); redirect($nonautorizedurl); exit(); } $_VARS['originalurl'] = ($_POST['originalurl'] ? $_POST['originalurl'] : $autorizedurl); $_VARS['url'] = $_SERVER['PHP_SELF']; if ($show) { _showpage('','smauth_login',$outer_html); return; } else { $page = _getpage('smauth_login'); return $page; } } ##Login ############################################################################ function Logoff ($redirect=null) ############################################################################ { global $LOGIN_TABLEPREFIX; global $TABLEPREFIX; global $ON_BEFORELOGOFF_PROC; global $LOGIN_USE_COOKIES; global $LOGIN_EXPIRES; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; $COOKIENAME = "{$tableprefix}simplelox"; $cookieexpire = $LOGIN_EXPIRES? (time()+60*$LOGIN_EXPIRES) : null; global $_VARS; $_VARS['_use_past_time_'] = 1; if (! $LOGIN_USE_COOKIES) { session_start(); session_regenerate_id(1); $cookie = $_SESSION[$COOKIENAME]; } else { $cookie = $_COOKIE[$COOKIENAME]; } if ( $cookie ) { db_query("update {$tableprefix}logins set logged_id=null,accessed_dt=" . mysql_now() ." where logged_id='$cookie'"); } if (! $LOGIN_USE_COOKIES) { $_SESSION[$COOKIENAME] = null; } else { setcookie($COOKIENAME,'',null,'/'); setcookie($COOKIENAME,'',$cookieexpire,'/'); } if ($SMAUTH_BEFORELOGOFF_PROC) { $SMAUTH_BEFORELOGOFF_PROC(); } unset($_VARS['smauth_user_id']); unset($_VARS['smauth_login']); unset($_VARS['smauth_title'] ); unset($_VARS['smauth_firstname'] ); unset($_VARS['smauth_lastname'] ); unset($_VARS['smauth_name'] ); if (isset($redirect)) { redirect($redirect); exit(); } } ##Logoff ############################################################################ function main_logoff() { Logoff($_SERVER['PHP_SELF']); } ############################################################################ function main_login() { Login($_SERVER['PHP_SELF'],$_SERVER['PHP_SELF'],1,'outer'); } ############################################################################ function main_useradmin() { ManageLogins(1,'outer',$_REQUEST['do_edit_me'] ? 'edit_me':null); } ############################################################################ function main_mydetails() { ManageMyLogin(1,'outer','edit_me'); } ############################################################################ function main_register() { if ($_REQUEST['thanks']) { $_VARS['register']=1; _showpage('','smauth_thanks','outer'); } else { RegisterLogin(1,'outer',$_SERVER['PHP_SELF']."?continue=1&thanks=1",'.'); } } ############################################################################ function main_unregister() { if ($_REQUEST['thanks']) main_unregister_thanks(); else if ($_POST['smauth_login_cancel']) redirect($_SERVER['PHP_SELF']); else if ($_POST['smauth_login_ok2']) main_unregister_ok2(); else if ($_POST['smauth_login_ok']) main_unregister_ok(); else _showpage('','smauth_unregister','outer'); } function main_unregister_thanks() { global $_VARS; $_VARS['unregister']=1; _showpage('','smauth_thanks','outer'); } function main_unregister_ok2() { global $TABLEPREFIX,$_VARS; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; db_query("delete from {$tableprefix}logins where id={$_VARS['smauth_user_id']}"); send_unreg_emails($_VARS['smauth_login']); unset($_VARS['smauth_user_id']); unset($_VARS['smauth_login']); if ($SMAUTH_AFTERUNREGISTER_PROC) { $SMAUTH_AFTERUNREGISTER_PROC(); } redirect($_SERVER['PHP_SELF']."?continue=1&thanks=1"); } function main_unregister_ok() { global $TABLEPREFIX,$_VARS; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; if ($_REQUEST['smauth_login']!=$_VARS['smauth_login']) { $_VARS['err'] = 'You are not logged in as '.$_REQUEST['smauth_login']; _showpage('','smauth_unregister','outer'); exit; } $key = db_escapeSimple(get_my_secret_key()); if ($key) { $login_fld = "decode(login,'$key')"; $passwd_fld = "decode(passwd,'$key') passwd"; } else { $login_fld = "login"; $passwd_fld = "passwd"; } $login = db_escapeSimple($_POST['smauth_login']); $passwd = db_escapeSimple($_POST['smauth_passwd']); $where = "$login_fld='$login'"; $res = db_getRow("select id,$passwd_fld from {$tableprefix}logins where $where"); $id = $res['id']; if ($id and $res['passwd']==$passwd) // passwd is case snstv! { $_VARS['ask_confirm']=1; _showpage('','smauth_unregister','outer'); exit; } else { $_VARS['err'] = 'Password is not correct'; _showpage('','smauth_unregister','outer'); exit; } } ############################################################################ function main_passwd() { if ($_REQUEST['ok']) main_passwd_ok(); else if ($_REQUEST['thanks']) main_passwd_default(); else main_passwd_default(); } function main_passwd_default() { global $_VARS; $_VARS['thanks'] = $_REQUEST['thanks']; _showpage('','smauth_fogottenpassword','outer'); } function main_passwd_ok() { global $TABLEPREFIX; global $_VARS; $login = db_escapeSimple($_REQUEST['email']); $passwd = db_getOne("select passwd from {$TABLEPREFIX}logins where login='$login'"); if ($passwd) { $text = db_getOne("select val from {$TABLEPREFIX}params where param='passwd_email2customer'"); $from = db_getOne("select val from {$TABLEPREFIX}params where param='email'"); $subject = "Automated response from Red Box"; $text = preg_replace('/#email#/',$_REQUEST['email'],$text); $text = preg_replace('/#password#/',$passwd,$text); $r1 = smmail($_REQUEST['email'], $subject, $text, $from); redirect($_SERVER['PHP_SELF']."?continue=1&thanks=yes"); } else { redirect($_SERVER['PHP_SELF']."?continue=1&thanks=no"); } } ############################################################################ function RegisterLogin($show=null,$outer_html=null,$url_on_success=null,$url_on_error=null) { return ManageLogins($show,$outer_html,'add_me',$url_on_success,$url_on_error); } ############################################################################ function ManageMyLogin($show=null,$outer_html=null) { return ManageLogins($show,$outer_html,'edit_me'); } ############################################################################ function ManageLogins($show=null,$outer_html=null,$mode=null,$url_on_success=null,$url_on_error=null) { global $LOGIN_TABLEPREFIX; global $TABLEPREFIX,$_VARS; $_VARS['_use_past_time_'] = 1; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; if ($mode != 'add_me') { CheckLogin(1,'',$outer_html); } if ($show and !$outer_html) $outer_html = 'outer'; $ida = &new InstantDbApp( array( 'debug'=>0, 'table'=>"{$tableprefix}logins", 'listFields'=>array('id','login','firstname','email','lastname','phone1'), 'fieldOptions'=>array( 'id'=>array('Type'=>'int','Len'=>'11','Null'=>'0','PK'=>'1','Default'=>null,'Caption'=>'id','Format'=>''), 'login'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>$_VARS['user_email'],'Caption'=>'Email','Format'=>'','Encrypt'=>1), 'passwd'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Password','Format'=>'','Encrypt'=>1), 'hint'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'hint','Format'=>'','Encrypt'=>1), 'hintanswer'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'hintanswer','Format'=>'','Encrypt'=>1), 'created_dt'=>array('Type'=>'datetime','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'created_dt','Format'=>''), 'updated_dt'=>array('Type'=>'datetime','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'updated_dt','Format'=>''), 'accessed_dt'=>array('Type'=>'datetime','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'accessed_dt','Format'=>''), 'session2expire'=>array('Type'=>'varchar','Len'=>'10','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'session2expire','Format'=>''), 'rights'=>array('Type'=>'text','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'rights','Format'=>'','Encrypt'=>1), 'title'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'title','Format'=>'','Encrypt'=>1), 'firstname'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Firstname','Format'=>'','Encrypt'=>1), 'middlename'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'middlename','Format'=>'','Encrypt'=>1), 'lastname'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Lastname','Format'=>'','Encrypt'=>1), 'address'=>array('Type'=>'text','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'address','Format'=>'','Encrypt'=>1), 'address2'=>array('Type'=>'text','Len'=>'','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'address2','Format'=>'','Encrypt'=>1), 'city'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'city','Format'=>'','Encrypt'=>1), 'county'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'county','Format'=>'','Encrypt'=>1), 'country'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'country','Format'=>'','Encrypt'=>1), 'postcode'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'postcode','Format'=>'','Encrypt'=>1), 'url'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'url','Format'=>'','Encrypt'=>1), 'phone1'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'phone','Format'=>'','Encrypt'=>1), 'phone2'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'phone','Format'=>'','Encrypt'=>1), 'company_name'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'company_name','Format'=>'','Encrypt'=>1), 'job_title'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'job_title','Format'=>'','Encrypt'=>1), 'role_id'=>array('Type'=>'int','Len'=>'11','Null'=>'1','PK'=>'0','Default'=>0,'Caption'=>'role_id','Format'=>''), ) ,pagesize=>20 ,sort=>'login' ,listHtml=>'smauth_user_list' ,editHtml=>'smauth_user_edit' ,viewHtml=>'smauth_user_edit' ,outerHtml=>$outer_html ,where=>"login not like '[%'" )); $ida->on_save = 'manage_logins_onsave'; $ida->on_after_save = 'manage_logins_onaftersave'; $ida->on_validate = 'manage_logins_onvali'; $ida->on_render = 'manage_logins_on_render'; $ida->on_dberr = "manage_logins_on_dberr"; $ida->on_get_encryption_key = "get_my_secret_key"; $ida->on_filter= "manage_logins_onfilter"; $ida->on_start = "manage_logins_onstart"; $_VARS['subtitle'] = 'Users'; if (! $ida->reusing ) { if ($mode == 'add_me') { $_REQUEST['do_add'] = 1; $_VARS['do_edit_me'] = 1; #$ida->cantadd = 1; $ida->cantdel = 1; #$ida->exit_edit_url = 'admin.php'; if (! $ida->exit_edit_url) { $ida->exit_edit_url = ($_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$_SERVER['PHP_SELF']); } $ida->userdata['do_edit_me'] = 1; $ida->userdata['do_login'] = 1; $ida->userdata['url_on_success'] = $url_on_success; $ida->userdata['url_on_error'] = $url_on_error; } else if (! GetUserRights('users') or ($mode == 'edit_me')) { $_REQUEST['do_edit'] = 1; $_REQUEST['db_id'] = $_VARS['smauth_user_id']; $ida->userdata['do_edit_me'] = 1; $_VARS['do_edit_me'] = 1; $ida->cantadd = 1; $ida->cantdel = 1; #$ida->exit_edit_url = 'admin.php'; if (! $ida->exit_edit_url) { $ida->exit_edit_url = ($_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$_SERVER['PHP_SELF']); } } } else { $_VARS['do_edit_me'] = $ida->userdata['do_edit_me']; if ($_VARS['do_edit_me']) { //$ida->cantadd = 1; $ida->cantdel = 1; } if (! $ida->exit_edit_url) { $ida->exit_edit_url = ($_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$_SERVER['PHP_SELF']); } } if ($show) { $ida->process($_REQUEST); return null; } else { ob_start(); $ida->process($_REQUEST); $text = ob_get_contents(); ob_end_clean(); return $text; } } ############################################################################## function manage_logins_onstart(&$ida,&$post) { global $_VARS; if ($ida->userdata['do_edit_me'] and $ida->process_name=='list') { $curl = ($_SERVER['HTTPS']?'https://':'http://') . $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']; if ($curl == $ida->exit_edit_url or preg_match('/\Wcontinue=1/',$ida->exit_edit_url)) $ida->exit_edit_url = $_SERVER['PHP_SELF']; redirect($ida->exit_edit_url); exit; } return 1; } ############################################################################## function manage_logins_on_render(&$ida,&$post) { global $LOGIN_TABLEPREFIX; global $TABLEPREFIX; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; global $_VARS; if ($_VARS['is_new']) { $_VARS['res']['passwd'] = ''; $_VARS['res']['passwd2'] = ''; if ($_VARS['user_email']) { $login=db_escapeSimple($_VARS['user_email']); $res = db_getRow("select * from {$tableprefix}logins where login='$login'"); $_VARS['res']['title' ] = htmlspecialchars($res ['title' ]); $_VARS['res']['firstname' ] = htmlspecialchars($res ['firstname' ]); $_VARS['res']['middlename' ] = htmlspecialchars($res ['middlename' ]); $_VARS['res']['lastname' ] = htmlspecialchars($res ['lastname' ]); $_VARS['res']['address' ] = htmlspecialchars($res ['address' ]); $_VARS['res']['address2' ] = htmlspecialchars($res ['address2' ]); $_VARS['res']['city' ] = htmlspecialchars($res ['city' ]); $_VARS['res']['county' ] = htmlspecialchars($res ['county' ]); $_VARS['res']['country' ] = htmlspecialchars($res ['country' ]); $_VARS['res']['postcode' ] = htmlspecialchars($res ['postcode' ]); $_VARS['res']['url' ] = htmlspecialchars($res ['url' ]); $_VARS['res']['phone1' ] = htmlspecialchars($res ['phone1' ]); $_VARS['res']['phone2' ] = htmlspecialchars($res ['phone2' ]); $_VARS['res']['company_name'] = htmlspecialchars($res ['company_name']); $_VARS['res']['job_title' ] = htmlspecialchars($res ['job_title' ]); } } return 1; } ############################################################################## function manage_logins_onvali(&$ida,&$p,&$err) { global $TABLEPREFIX,$_VARS; global $LOGIN_TABLEPREFIX; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; if (isset($p['db_passwd2']) and $p['db_passwd2']!=$p['db_passwd']) { array_push($err,'Password & Confirm Password are not the same!'); return 0; } if ($p['is_new']) { $login = db_escapeSimple($p['db_login']); $id = db_getOne("select id from {$tableprefix}logins where login='$login' and passwd !=''"); if ($id) { array_push($err,'You already have an account with us. Please login to update your profile'); return 0; } } /* if (strlen($p['db_passwd']) < 6) { array_push($err,'Password must be at least 6 chars'); return 0; } if ($p['db_passwd']==$p['db_login']) { array_push($err,'Password cannot repeat user name'); return 0; } if ( $p['db_passwd']=='123456' or $p['db_passwd']=='1234567' or $p['db_passwd']=='12345678' or $p['db_passwd']=='123456789' ) { array_push($err,'Bad password'); return 0; } */ return 1; } ############################################################################## function manage_logins_onsave(&$ida,&$p) { global $TABLEPREFIX,$_VARS; global $LOGIN_TABLEPREFIX; $tableprefix = $LOGIN_TABLEPREFIX ? $LOGIN_TABLEPREFIX : $TABLEPREFIX; if (! $p['db_created_dt']) $p['db_created_dt'] = strftime('%Y.%m.%d %H:%M'); $p['db_updated_dt'] = strftime('%Y.%m.%d %H:%M'); if ($p['is_new']) { $login = db_escapeSimple($p['db_login']); db_query("delete from {$tableprefix}logins where login='$login'"); } return 1; } ############################################################################## function manage_logins_onaftersave(&$ida,&$p) { if ($ida->userdata['do_edit_me']) { if ($p['is_new']) { send_reg_emails($p); } /* else { send_upd_emails($p); } */ } if ($ida->userdata['do_login'] ) { $_POST['smauth_login_ok'] = 1; $_POST['smauth_login'] = $p['db_login']; $_POST['smauth_passwd'] = $p['db_passwd']; $_POST['originalurl'] = ($ida->userdata['url_on_success'] ? $ida->userdata['url_on_success'] : $ida->exit_edit_url); Logoff(); Login(); } return 1; } ############################################################################## function manage_logins_on_dberr(&$apps,$why,$errno,&$err){ global $_VARS; if ($why=='save' and $errno==1062) { $err = 'Duplicate entry for email. Please choose another email'; } return 1; } ############################################################################ function manage_logins_onfilter(&$ida,&$post) { global $_VARS; if ($post['filter_login']) $ida->andWhereSmartEqual("login","{$post['filter_login']}*"); if ($post['filter_firstname']) $ida->andWhereSmartEqual("firstname","{$post['filter_firstname']}*"); if ($post['filter_lastname']) $ida->andWhereSmartEqual("lastname","{$post['filter_lastname']}*"); return 1; // autosave post data (not 'where' - it will be saved in any case) } ############################################################################## function get_my_secret_key($ida=null) { global $PHRASE; if (!$PHRASE) { //pdebug("PHRASE is null"); return null; } $k = base64_encode($PHRASE); while(strlen($k)<27) $k .= $k; $k=substr($k,14,27); return $k; } ?> php /*! \file util.inc.php \brief Contains common functions */ /*! \fn SmartStrToDate \brief Replacement for standard strtotime function */ function SmartStrToDate($v) { if (preg_match('/^\s*$/',$v)) return strtotime(''); $a = array(); preg_match('/^\s*(\d{1,4})\s*(\/|\.| |\-)?\s*((\d{1,2})|([A-Za-z]+))\s*(\/|\.| |\-)?\s*(\d{0,4})\s*((\+|\-)\s*(\d+)\s*([A-Za-z]+))?\s*$/' ,$v,$a); /* echo "v=".$v."\n"; echo "d=".$a[1]."\n"; echo "m=".$a[3]."\n"; echo "y=".$a[7]."\n"; echo "plusminus=".$a[9]."\n"; echo "num=".$a[10]."\n"; echo "what=".$a[11]."\n"; */ $d= $a[1]; $m=$a[3]; $y=$a[7]; if ($d>1000) { $d= $a[7]; $y=$a[1]; } /* echo "d=".$a[1]."\n"; echo "m=".$a[3]."\n"; echo "y=".$a[7]."\n"; echo "plusminus=".$a[9]."\n"; echo "num=".$a[10]."\n"; echo "what=".$a[11]."\n"; */ $plusminus=$a[9]; $num=$a[10]; $what=$a[11]; if (!$d or $m==null or $m=="") { preg_match('/^\s*(\+|\-)\s*(\d+)\s*([A-Za-z]+)\s*$/' ,$v,$a); $plusminus=$a[1]; $num=$a[2]; $what=$a[3]; if (!$plusminus) return -1; $tm = localtime(); $d = $tm[3]; $m = $tm[4]+1; $y = $tm[5]+1900; /* echo "plusminus=".$plusminus."\n"; echo "num=".$num."\n"; echo "what=".$what."\n"; echo "d=".$d."\n"; echo "m=".$m."\n"; echo "y=".$y."\n"; */ } if ($y==null or $y=='') $y = strftime('%Y'); if ($y<38) $y += 2000; else if ($y<100) $y += 1900; if (!preg_match('/^\d+$/',$m)) { $m = strtolower($m); if (preg_match("/^$m/",'january') and preg_match("/^ja/",$m)) $m=1; else if (preg_match("/^$m/",'february') and preg_match("/^f/",$m)) $m=2; else if (preg_match("/^$m/",'march') and preg_match("/^mar/",$m)) $m=3; else if (preg_match("/^$m/",'april') and preg_match("/^ap/",$m)) $m=4; else if (preg_match("/^$m/",'may') and preg_match("/^may/",$m)) $m=5; else if (preg_match("/^$m/",'june') and preg_match("/^jun/",$m)) $m=6; else if (preg_match("/^$m/",'july') and preg_match("/^jul/",$m)) $m=7; else if (preg_match("/^$m/",'august') and preg_match("/^au/",$m)) $m=8; else if (preg_match("/^$m/",'september') and preg_match("/^s/",$m)) $m=9; else if (preg_match("/^$m/",'october') and preg_match("/^o/",$m)) $m=10; else if (preg_match("/^$m/",'november') and preg_match("/^n/",$m)) $m=11; else if (preg_match("/^$m/",'december') and preg_match("/^d/",$m)) $m=12; else return -1; } if (!checkdate($m,$d,$y)) return -1; $dt = strtotime("$m/$d/$y"); if ($what) { $what = strtolower($what); if (preg_match("/^$what/",'days')) $what='day'; else if (preg_match("/^$what/",'weeks')) $what='week'; else if (preg_match("/^$what/",'months')) $what='month'; else if (preg_match("/^$what/",'years')) $what='year'; else return -1; if ($plusminus=="" or $plusminus==null) return -1; } if ($plusminus!=null and $plusminus!="" and $plusminus!="+" and $plusminus!="-") return -1; if ($what=='year') { if ($plusminus=='-') $num = -$num; $y += $num; if (!checkdate($m,$d,$y)) --$d; $plusminus=null; $num=null; $what=null; } else if ($what=='month') { if ($plusminus=='-') $num = -$num; $m += $num; while($m>12) { $m -= 12; $y++; } while($m<1) { $m += 12; $y--; } if (!checkdate($m,$d,$y)) --$d; if (!checkdate($m,$d,$y)) --$d; if (!checkdate($m,$d,$y)) --$d; if (!checkdate($m,$d,$y)) --$d; $plusminus=null; $num=null; $what=null; } /* echo "d=".$d."\n"; echo "m=".$m."\n"; echo "y=".$y."\n"; echo "plusminus=".$plusminus."\n"; echo "num=".$num."\n"; echo "what=".$what . "\n"; */ $dt = strtotime("$m/$d/$y$plusminus$num$what"); return $dt; } ############################################################################## # debug funcitons ############################################################################## function pdebug($x=null) { if (is_array($x)) { $x = join(',',$x); } echo "=====[$x]=====
"; } ############################################################################## function PutLog ($s) { global $_VARS,$TABLEPREFIX; $now=getdate(); $date=sprintf('%04d-%02d-%02d',$now['year'],$now['mon'],$now['mday']); $time=sprintf('%04d-%02d-%02d %02d:%02d:%02d',$now['year'],$now['mon'],$now['mday'],$now['hours'],$now['minutes'],$now['seconds']); $me=$_SERVER['PHP_SELF']; $ip=$_SERVER['REMOTE_ADDR']; $ua=$_SERVER['HTTP_USER_AGENT']; if (!is_dir('logs')) mkdir('logs', 0777 ); $file = fopen("logs/{$date}_{$TABLEPREFIX}_log.log", "a"); if (!$file) { echo("Can't open file..."); }else { fputs($file,"$time [$me] [$ip] [$ua]:\n$s\n\n"); fclose($file); } } ############################################################################## function mysql_now() { return date("'Y/m/d H:i:s'"); } ############################################################################## function smmail($to,$subject,$text,$from) { $ct = preg_match('/ php function &art_construct($listHtml=null,$editHtml=null,$viewHtml=null,$outerHtml=null) { global $TABLEPREFIX; global $_VARS; if (!$listHtml ) $listHtml ='article_l'; if (!$editHtml ) $editHtml ='article_e'; if (!$viewHtml ) $viewHtml ='article_pv'; if (!$outerHtml) $outerHtml='outer'; $ida = & new InstantDbApp( array( 'name'=>"{$TABLEPREFIX}articles_$listHtml", 'table'=>"{$TABLEPREFIX}articles", 'listFields'=>array('id','dt','headline','subheadline','author','authorprofile','txt','opts'), 'fieldOptions'=>array( 'id'=>array('Type'=>'int','Len'=>'11','Null'=>'0','PK'=>'1','Default'=>null,'Caption'=>'id','Format'=>null), 'dt'=>array('Type'=>'datetime','Len'=>null,'Null'=>'0','PK'=>'0','Default'=>"?=date('d/m/Y H:i')",'Caption'=>'Date','Format'=>null), 'headline'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Headline','Format'=>null), 'subheadline'=>array('Type'=>'varchar','Len'=>'255','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'Sub-headline','Format'=>null), 'keywords'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Keywords','Format'=>null), 'txt'=>array('Type'=>'text','Len'=>null,'Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Text','Format'=>null), 'author'=>array('Type'=>'varchar','Len'=>'255','Null'=>'0','PK'=>'0','Default'=>null,'Caption'=>'Author','Format'=>null), 'authorprofile'=>array('Type'=>'text','Len'=>null,'Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'AuthorProfile','Format'=>null), 'month'=>array('Type'=>'varchar','Len'=>'10','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'Month','Format'=>null), 'published'=>array('Type'=>'tinyint','Len'=>'4','Null'=>'1','PK'=>'0','Default'=>1,'Caption'=>'Published','Format'=>null), 'opts'=>array('Type'=>'varchar','Len'=>'20','Null'=>'1','PK'=>'0','Default'=>null,'Caption'=>'Options','Format'=>null) ) ,'debug' => 0 ,'generate_list' => 0 ,'generate_edit' => 0 ,'listHtml' => $listHtml ,'editHtml' => $editHtml ,'viewHtml' => $viewHtml ,'outerHtml' =>$outerHtml ,'pagesize' => 10 ,'sort' => 'dt-' )); return $ida; } ############################################################################## function send_upd_emails($p) { global $_VARS,$TABLEPREFIX; $text = db_getOne("select val from {$TABLEPREFIX}params where param='upd_email2customer'"); $from = db_getOne("select val from {$TABLEPREFIX}params where param='email'"); $subject = "Latest from City Girl"; $text = preg_replace('/#email#/',$p['db_login'],$text); $text = preg_replace('/#name#/',"{$p['db_firstname']} {$p['db_lastname']}" ,$text); $r1 = mail($p['db_login'], $subject, $text, "From: $from"); $text = db_getOne("select val from {$TABLEPREFIX}params where param='upd_email2admin'"); $to = db_getOne("select val from {$TABLEPREFIX}params where param='admin_email'"); $text = preg_replace('/#email#/',$p['db_login'],$text); $text = preg_replace('/#name#/',"{$p['db_firstname']} {$p['db_lastname']}" ,$text); $r2 = mail($to, $subject, $text, "From: $from"); } ############################################################################## function send_reg_emails($p) { global $_VARS,$TABLEPREFIX; $text = db_getOne("select val from {$TABLEPREFIX}params where param='reg_email2customer'"); $from = db_getOne("select val from {$TABLEPREFIX}params where param='email'"); $subject = "Automated response from City Girl"; $text = preg_replace('/#email#/',$p['db_login'],$text); $text = preg_replace('/#password#/',$p['db_passwd'] ,$text); $text = preg_replace('/#name#/',"{$p['db_firstname']} {$p['db_lastname']}" ,$text); $r1 = smmail($p['db_login'], $subject, $text, $from); $text = db_getOne("select val from {$TABLEPREFIX}params where param='reg_email2admin'"); $to = db_getOne("select val from {$TABLEPREFIX}params where param='admin_email'"); $text = preg_replace('/#email#/',$p['db_login'],$text); $text = preg_replace('/#name#/',"{$p['db_firstname']} {$p['db_lastname']}" ,$text); $r2 = smmail($to, $subject, $text, $from); } ############################################################################## function send_unreg_emails($email) { global $_VARS,$TABLEPREFIX; $text = db_getOne("select val from {$TABLEPREFIX}params where param='unreg_email2customer'"); $from = db_getOne("select val from {$TABLEPREFIX}params where param='email'"); $subject = "Automated response from City Girl"; $text = preg_replace('/#email#/',$email,$text); $r1 = smmail($email, $subject, $text, $from); $text = db_getOne("select val from {$TABLEPREFIX}params where param='unreg_email2admin'"); $to = db_getOne("select val from {$TABLEPREFIX}params where param='admin_email'"); $text = preg_replace('/#email#/',$email,$text); $r2 = smmail($to, $subject, $text, $from); } ############################################################################## function make_summary($t) { $t = strip_tags($t); $i1 = strpos($t,'.'); $i2 = strpos($t,'!'); $i3 = strpos($t,'?'); if ($i1===false) $i1 = 200; if ($i2===false) $i2 = 200; if ($i3===false) $i3 = 200; $i=min($i1,$i2,$i3); $t = substr($t,0,$i+1); $maxwords = 40; $spc=0; for($i=0;$i=$maxwords) { $t = substr($t,0,$i) . '...'; break; } } return $t; } ############################################################################## function MakeSafeText($t) { $t = preg_replace('/\n/','
',$t); $t = preg_replace('/(<)(\/?script[^>]*)(>)/','<$2>',$t); return $t; } ############################################################################## function MakeHttpLinksText($t) { $t = preg_replace('/([^>\'\"]|^)(http\:\/\/[^\s\n)\"\']+)([^<\'\"]|$)/',"$1$2$3",$t); $t = preg_replace('/([^>\'\"\/\/]|^)(www\.[^\s\n)\"\']+)([^>\'\"]|$)/',"$1$2$3",$t); return $t; } ?>