Revert "DataObjects/Events.php"
authorAlan Knowles <alan@akbkhome.com>
Sat, 31 Mar 2012 07:55:22 +0000 (15:55 +0800)
committerAlan Knowles <alan@akbkhome.com>
Sat, 31 Mar 2012 07:55:22 +0000 (15:55 +0800)
This reverts commit 3114b4c436bd5c5fc9196ee02b751a682b6bc0a5.

DataObjects/Events.php [new file with mode: 0644]
DataObjects/Person.php [new file with mode: 0644]
DataObjects/core.sql [new file with mode: 0644]

diff --git a/DataObjects/Events.php b/DataObjects/Events.php
new file mode 100644 (file)
index 0000000..9c64b5c
--- /dev/null
@@ -0,0 +1,315 @@
+<?php
+/**
+ * Table Definition for Events
+ *
+ * objects can implement relatedWhere(), which should return
+ *    'tablename' => array of ids
+ *
+ * 
+ */
+require_once 'DB/DataObject.php';
+
+class Pman_Core_DataObjects_Events extends DB_DataObject 
+{
+    ###START_AUTOCODE
+    /* the code below is auto generated do not remove the above tag */
+
+    public $__table = 'Events';                          // table name
+    public $id;                              // int(11)  not_null primary_key auto_increment
+    public $person_name;                     // string(128)  
+    public $event_when;                      // datetime(19)  binary
+    public $action;                          // string(32)  
+    public $ipaddr;                          // string(16)  
+    public $on_id;                           // int(11)  
+    public $on_table;                        // string(64)  
+    public $person_id;                       // int(11)  
+    public $remarks;                         // blob(65535)  blob
+
+    
+    /* the code above is auto generated do not remove the tag below */
+    ###END_AUTOCODE
+    
+    
+    
+    
+    //  ------------ROO HOOKS------------------------------------
+    function applyFilters($q, $au)
+    {
+        $tn = $this->tableName();
+        if (!empty($q['query']['from'])) {
+            $dt = date('Y-m-d' , strtotime($q['query']['from']));
+            $this->whereAdd(" {$tn}.event_when >=  '$dt' ");
+        }
+        if (!empty($q['query']['to'])) {
+            $dt = date('Y-m-d' , strtotime($q['query']['to']));
+            $this->whereAdd(" {$tn}.event_when <=  '$dt' ");
+        }
+        /*
+        if (!empty($q['query']['grouped']) && $q['query']['grouped'] == 'gr') {
+            // grouped..
+            DB_DataObject::Debuglevel(1);
+            $this->groupBy('on_id');
+            $this->selectAdd('
+                (SELECT count(id) FROM core_event_audit WHERE event_id = Events.id) as changed
+                ');
+        }
+        */
+        
+        if (!$au->hasPerm("Admin.Admin_Tab", 'S')) {
+            //DB_DataObject::DebugLevel(1);
+            // they can only view their changes..
+            $this->person_id = $au->id;
+            
+        }
+        // _join = tablename,tablename...
+        
+        /// on_table=cohead
+        //   &_join=cohead
+        //   &_join_cols=cohead_number
+        //    &_columns=on_id_cohead_number,event_when << this is ignored at present.
+        // max(event_when) is not supported... by any query yet..
+        
+        if (isset($q['on_table']) && !strlen($q['on_table'])) {
+            // empty ontable queries.. these are valid..
+            $this->whereAdd("$tn.on_table = ''");
+        }
+        
+        
+        if (isset($q['query']['person_sum'])) {
+            //DB_DataObject::debugLevel(1);
+            $this->_extra_cols = array('qty' );
+            $this->selectAdd("count($tn.id) as qty");
+            $this->selectAdd("count( distinct $tn.on_id) as uqty");
+            $this->whereAdd('LENGTH(join_person_id_id.name) > 0 ');
+            $this->groupBy('person_id');
+        }
+         if (isset($q['query']['table_sum'])) {
+            //DB_DataObject::debugLevel(1);
+            $this->_extra_cols = array('qty' , 'uqty');
+            $this->selectAdd("count($tn.id) as qty");
+            $this->selectAdd("count( distinct $tn.on_table, $tn.on_id) as uqty");
+            
+            $this->groupBy('on_table');
+        }
+         if (isset($q['query']['day_sum'])) {
+            //DB_DataObject::debugLevel(1);
+            $this->_extra_cols = array('qty' , 'uqty');
+            $this->selectAdd("DATE_FORMAT(event_when, '%Y-%m-%d') as on_day");
+            $this->selectAdd("count($tn.id) as qty");
+            $this->selectAdd("count( distinct $tn.on_id) as uqty");
+            
+            $this->groupBy('on_day');
+        }
+        
+        if (isset($q['_join'])) {
+            //DB_DataObject::DebugLevel(1);
+            $joins = explode(',',$q['_join']);
+            
+            $this->selectAdd(); // ???
+            $distinct = false;
+            
+            foreach($joins as $t) {
+                $t = preg_replace('/[^a-z_]+/', '', $t); // protection.
+                $x = DB_DataObject::Factory($t);
+                if (!is_a($x,'DB_DataObject')) {
+                    continue;
+                }
+                $jtn = $x->tableName();
+                $jk = array_shift($x->keys());
+                $this->_join .= "
+                
+                    LEFT JOIN {$jtn} as join_on_id_{$jtn} ON {$tn}.on_id = join_on_id_{$jtn}.{$jk}
+                        AND on_table = '{$jtn}'
+                ";
+                $keys = array_keys($x->table());
+                if (isset($q['_join_cols'])) {
+                    $jcs = explode(',',$q['_join_cols'] );
+                    //DB_DataObject::DebugLevel(1);
+                    
+                    foreach($jcs as $jc) { 
+                        if (! in_array($jc, $keys)) {
+                            continue;
+                        }
+                        if ($distinct) { 
+                        
+                       
+                            $this->selectAdd( " join_on_id_{$jtn}.{$jc}   as on_id_{$jc} ");
+                        } else {
+                            $this->selectAdd( " distinct(join_on_id_{$jtn}.{$jc}  ) as on_id_{$jc} ");
+                            $distinct = true;
+                        }
+                        $this->groupBy("on_id_{$jc} ");
+                        $this->whereAdd("join_on_id_{$jtn}.{$jc} IS NOT NULL");
+                    }
+                    $this->selectAdd( "MAX(events.event_when) as event_when");
+                    $this->orderBy('event_when DESC');
+                   // $this->selectAs(array($q['_join_cols']) , 'on_id_%s', "join_on_id_{$jtn}");
+                } else { 
+                    $this->selectAs($x, 'on_id_%s', "join_on_id_{$jtn}");
+                }
+            }
+                
+                
+            
+            
+        }
+        
+        if (isset($q['_related_on_id']) && isset($q['_related_on_table'])) {
+            // example: sales order - has invoices,
+            $ev  =$this->factory('Events');
+            $ev->setFrom(array(
+                'on_id' => $q['_related_on_id'],
+                'on_table' => $q['_related_on_table'],
+                               ));
+            $obj = $ev->object();
+            
+            if ($obj && method_exists($obj,'relatedWhere')) {
+                $ar = $obj->relatedWhere();
+                $tn = $this->tableName();
+                
+                $w = array();
+                $w[] = "( {$tn}.on_table = '" .
+                        $this->escape($q['_related_on_table']) .
+                        "' AND {$tn}.on_id = ". ((int)  $q['_related_on_id']) .
+                    ")";
+                
+                
+                foreach($ar as $k=>$v) {
+                    if (empty($v)) {
+                        continue;
+                    }                
+                     $w[] = "( {$tn}.on_table = '$k' AND {$tn}.on_id IN (". implode(',', $v). "))";
+                    
+                }
+                $this->whereAdd(implode(' OR ' , $w));
+            }
+            
+            
+            
+            
+            
+        }
+        
+        
+        
+        
+        
+            
+    }
+    /**
+     * check who is trying to access this. false == access denied..
+     * @return {boolean} true if access is allowed.
+     */
+    function checkPerm($lvl, $au) 
+    {
+        if ($lvl == 'S') {
+            return true;
+        }
+        // listing is controleed by applyfilters..
+        return $au->hasPerm("Admin.Admin_Tab", 'S');
+    }
+    /**
+     * object :
+     * return the object that this relates to.
+     * 
+     * @return {DB_DataObject} related object
+     */
+    function object()
+    {
+        $o = DB_DataObject::factory($this->on_table);
+        $o->get($this->on_id);
+        return $o;
+        
+    }
+    
+    
+    /**
+     * init:
+     * Initialize an event - ready to insert..
+     * 
+     * @param {String} action  - group/name of event
+     * @param {DataObject|false} obj - dataobject action occured on.
+     * @param {String} any remarks 
+     */
+    
+    function init($act, $obj, $remarks)
+    {
+        $ff = HTML_FlexyFramework::get();
+        $pg = $ff->page;
+        $au = $pg->getAuthUser();
+        
+        if ($ff->cli) { // && empty($au) && isset($obj->person_id)) {
+            $au = false;
+           // $au = DB_DataObject::Factory('Person'); // not always a person..
+           // $au->get($obj->person_id);
+        } 
+         
+         
+         
+        $this->person_name = $au && !empty($au->name) ? $au->name : '';
+        $this->person_id = $au ? $au->id : -1;
+        $this->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
+        $this->action = $act;
+        $this->on_table = $obj ? $obj->tableName() : '';
+        $pk = $obj ? $obj->keys()  : false;
+        $this->on_id  = $obj && $pk ? $obj->{$pk[0]}: 0;
+        $rem  = array();
+        // should this really go in remarks? - 
+        if ($obj && method_exists($obj,'toEventString')) {
+            $rem[] = $obj->toEventString() ;
+        }
+        $rem[] = $remarks;
+        $this->remarks = implode(' : ', $rem);
+    }
+    
+    /**
+     * Generate an audit for this field.
+     *
+     * @param {DB_DataObject} new data
+     * @param {DB_DataObject} old data
+     * 
+     * @return {int} number of entries logged.
+     */
+    
+    function audit($new, $old = false)
+    {
+        if ($old == $new) {
+            return 0; // they are the same...
+        }
+         
+        $ret = 0;
+        foreach(array_keys($new->table()) as $k) {
+            // should we JSON serialize this?
+            $n = empty($new->$k) ? '' : $new->$k;
+            $o = empty($old->$k) || empty($old->$k) ? '' : $old->$k;
+            if ($n == $o) {
+                continue;
+            }
+            $this->auditField($k, $o, $n, $old);
+            $ret++;
+        }
+        return $ret;
+    }
+    /**
+     * Record an audited change, in theory so we can audit data that is not just
+     * database Fields...
+     *
+     * @param {string} $name    table field anme
+     * @param {mixed} $ov  old value
+     * @param {mixed} $onv  new value
+     * @param {mixed} $old  old object (false if we are creating..)
+     */
+    function auditField($name, $ov, $nv, $old=false )
+    {
+        $x = DB_DataObject::factory('core_event_audit');
+        $x->setFrom(array(
+            'event_id' => $this->id,
+            'name' => $name,
+            'old_audit_id' => $old ? $x->findLast($this, $name) : 0,
+            'newvalue' => $nv
+
+        ));
+        $x->insert();
+    
+    }
+}
diff --git a/DataObjects/Person.php b/DataObjects/Person.php
new file mode 100644 (file)
index 0000000..8091c0e
--- /dev/null
@@ -0,0 +1,745 @@
+<?php
+/**
+ * Table Definition for Person
+ */
+require_once 'DB/DataObject.php';
+
+class Pman_Core_DataObjects_Person extends DB_DataObject 
+{
+    ###START_AUTOCODE
+    /* the code below is auto generated do not remove the above tag */
+
+    public $__table = 'Person';                          // table name
+    public $id;                              // int(11)  not_null primary_key auto_increment
+    public $office_id;                       // int(11)  
+    public $name;                            // string(128)  not_null
+    public $phone;                           // string(32)  not_null
+    public $fax;                             // string(32)  not_null
+    public $email;                           // string(128)  not_null
+    public $company_id;                      // int(11)  
+    public $role;                            // string(32)  not_null
+    public $active;                          // int(11)  not_null
+    public $remarks;                         // blob(65535)  not_null blob
+    public $passwd;                          // string(64)  not_null
+    public $owner_id;                        // int(11)  not_null
+    public $lang;                            // string(8)  
+    public $no_reset_sent;                   // int(11)  
+    public $action_type;                     // string(32)  
+    public $project_id;                      // int(11)  
+    public $deleted_by;                      // int(11)  not_null
+    public $deleted_dt;                      // datetime(19)  binary
+
+    
+    /* the code above is auto generated do not remove the tag below */
+    ###END_AUTOCODE
+    /**
+     *
+     * @param {String} $templateFile  (mail/XXXXXXX.txt) exclude the mail and .txt bit.
+     * @param {Array|Object} $args   data to send out..
+     * @return {Array|PEAR_Error} array of $recipents, $header, $body 
+     */
+    function buildMail($templateFile, $args)
+    {
+          
+        $args = (array) $args;
+        $content  = clone($this);
+        
+        foreach((array)$args as $k=>$v) {
+            $content->$k = $v;
+        }
+        
+        $ff = HTML_FlexyFramework::get();
+        
+        
+        //?? is this really the place for this???
+        if (
+                !$ff->cli && 
+                empty($args['no_auth']) &&
+                !in_array($templateFile, array(
+                    // templates that can be sent without authentication.
+                     'password_reset' ,
+                     'password_welcome'
+                 ))
+            ) {
+            
+            $content->authUser = $this->getAuthUser();
+            if (!$content->authUser) {
+                return PEAR::raiseError("Not authenticated");
+            }
+        }
+        
+        // should handle x-forwarded...
+        
+        $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
+            $_SERVER["HTTP_HOST"] :
+            (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
+            
+        /* use the regex compiler, as it doesnt parse <tags */
+        require_once 'HTML/Template/Flexy.php';
+        $template = new HTML_Template_Flexy( array(
+            'compiler'    => 'Flexy',
+            'nonHTML' => true,
+            'filters' => array('SimpleTags','Mail'),
+            //     'debug'=>1,
+        ));
+        
+     
+         
+        
+        $template->compile("mail/$templateFile.txt");
+        
+        /* use variables from this object to ouput data. */
+        $mailtext = $template->bufferedOutputObject($content);
+        //echo "<PRE>";print_R($mailtext);
+        //print_R($mailtext);exit;
+        /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
+        require_once 'Mail/mimeDecode.php';
+        require_once 'Mail.php';
+        
+        $decoder = new Mail_mimeDecode($mailtext);
+        $parts = $decoder->getSendArray();
+        if (PEAR::isError($parts)) {
+            return $parts;
+            //echo "PROBLEM: {$parts->message}";
+            //exit;
+        } 
+        list($recipents,$headers,$body) = $parts;
+        $recipents = array($this->email);
+        if (!empty($content->bcc) && is_array($content->bcc)) {
+            $recipents =array_merge($recipents, $content->bcc);
+        }
+        $headers['Date'] = date('r');
+        
+        return array(
+            'recipients' => $recipents,
+            'headers'    => $headers,
+            'body'      => $body
+        );
+        
+        
+    }
+    
+    
+    /**
+     * send a template
+     * - user must be authenticate or args[no_auth] = true
+     *   or template = password_[reset|welcome]
+     * 
+     */
+    function sendTemplate($templateFile, $args)
+    {
+        
+        $ar = $this->buildMail($templateFile, $args);
+      
+        
+        //print_r($recipents);exit;
+        $mailOptions = PEAR::getStaticProperty('Mail','options');
+        $mail = Mail::factory("SMTP",$mailOptions);
+        
+        if (PEAR::isError($mail)) {
+            return $mail;
+        } 
+        $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
+        $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
+        error_reporting($oe);
+       
+        return $ret;
+    
+    }
+    
+  
+    
+    
+    function getEmailFrom()
+    {
+        return '"' . addslashes($this->name) . '" <' . $this->email . '>';
+    }
+    function toEventString() 
+    {
+        return empty($this->name) ? $this->email : $this->name;
+    } 
+    function verifyAuth()
+    { 
+        $ff= HTML_FlexyFramework::get();
+        if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
+            $ff->page->jerr("Login not permited to outside companies");
+        }
+        return true;
+        
+    }    
+   
+   
+    //   ---------------- authentication / passwords and keys stuff  ----------------
+    function isAuth()
+    {
+        $db = $this->getDatabaseConnection();
+        // we combine db + project names,
+        // otherwise if projects use different 'auth' objects
+        // then we get unserialize issues.
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        
+        
+        @session_start();
+        if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
+            // in session...
+            $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
+            
+            $u = DB_DataObject::factory('Person');
+            if ($u->get($a->id)) { //&& strlen($u->passwd)) {
+                $u->verifyAuth();
+                
+                return true;
+            }
+            
+            $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
+            
+        }
+        // local auth - 
+        $u = DB_DataObject::factory('Person');
+        $ff = HTML_FlexyFramework::get();
+        if (!empty($ff->Pman['local_autoauth']) && 
+            (!empty($_SERVER['SERVER_ADDR'])) &&
+            ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
+            ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
+            $u->get('email', $ff->Pman['local_autoauth'])
+        ) {
+            $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
+            return true;
+        }
+           
+        
+        // not in session or not matched...
+        $u = DB_DataObject::factory('Person');
+        $u->whereAdd(' LENGTH(passwd) > 0');
+        $n = $u->count();
+        $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
+        if ($error) {
+            die($error->toString()); // not really a good thing to do...
+        }
+        if (!$n){ // authenticated as there are no users in the system...
+            return true;
+        }
+        
+        return false;
+        
+    }
+    function getAuthUser()
+    {
+        if (!$this->isAuth()) {
+            return false;
+        }
+        $db = $this->getDatabaseConnection();
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        
+        if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
+            $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
+            
+            $u = DB_DataObject::factory('Person');
+            if ($u->get($a->id)) { /// && strlen($u->passwd)) {
+                return clone($u);
+            }
+             
+        }
+        
+        $u = DB_DataObject::factory('Person');
+        $u->whereAdd(' LENGTH(passwd) > 0');
+        if (!$u->count()){
+            $u = DB_DataObject::factory('Person');
+            $u->id = -1;
+            return $u;
+            
+        }
+        return false;
+    }     
+    function login()
+    {
+        $this->isAuth(); // force session start..
+        $this->verifyAuth();
+        $db = $this->getDatabaseConnection();
+        // refresh admin group if we are logged in as one..
+        //DB_DataObject::debugLevel(1);
+        $g = DB_DataObject::factory('Groups');
+        $g->type = 0;
+        $g->get('name', 'Administrators');
+        $gm = DB_DataObject::Factory('Group_Members');
+        if (in_array($g->id,$gm->listGroupMembership($this))) {
+            // refresh admin groups.
+            $gr = DB_DataObject::Factory('Group_Rights');
+            $gr->applyDefs($g, 0);
+        }
+             
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
+        
+    }
+    function logout()
+    {
+        $this->isAuth(); // force session start..
+         $db = $this->getDatabaseConnection();
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
+        
+    }    
+    function genPassKey ($t) 
+    {
+        return md5($this->email . $t. $this->passwd);
+    }
+    function simpleAuthKey($m = 0)
+    {
+        $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
+        
+        return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
+    } 
+    function checkPassword($val)
+    {
+        
+        if (substr($this->passwd,0,1) == '$') {
+            return crypt($val,$this->passwd) == $this->passwd ;
+        }
+        // old style md5 passwords...- cant be used with courier....
+        return md5($val) == $this->passwd;
+    }
+    function setPassword($value) 
+    {
+        $salt='';
+        while(strlen($salt)<9) {
+            $salt.=chr(rand(64,126));
+            //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
+        }
+        $this->passwd = crypt($value, '$1$'. $salt. '$');
+       
+       
+    }      
+    
+    function company()
+    {
+        $x = DB_DataObject::factory('Companies');
+        $x->get($this->company_id);
+        return $x;
+    }
+    
+    
+    function active()
+    {
+        return $this->active;
+    }
+    function authUserName($n) // set username prior to acheck user exists query.
+    {
+        
+        $this->whereAdd('LENGTH(passwd) > 1'); 
+        $this->email = $n;
+    }
+    function lang($val)
+    {
+        if ($val == $this->lang) {
+            return;
+        }
+        $uu = clone($this);
+        $this->lang = $val;
+        $this->update($uu);
+
+    }
+            
+    
+    function authUserArray()
+    {
+        
+        $aur = $this->toArray();
+        
+        if ($this->id < 1) {
+            return $aur;
+        }
+        
+        
+        //DB_DataObject::debugLevel(1);
+        $c = DB_Dataobject::factory('Companies');
+        $im = DB_Dataobject::factory('Images');
+        $c->joinAdd($im, 'LEFT');
+        $c->selectAdd();
+        $c->selectAs($c, 'company_id_%s');
+        $c->selectAs($im, 'company_id_logo_id_%s');
+        $c->id = $this->company_id;
+        $c->limit(1);
+        $c->find(true);
+        
+        $aur = array_merge( $c->toArray(),$aur);
+        
+        if (empty($c->company_id_logo_id_id))  {
+                 
+            $im = DB_Dataobject::factory('Images');
+            $im->ontable = 'Companies';
+            $im->onid = $c->id;
+            $im->imgtype = 'LOGO';
+            $im->limit(1);
+            $im->selectAdd();
+            $im->selectAs($im,  'company_id_logo_id_%s');
+            if ($im->find(true)) {
+                    
+                foreach($im->toArray() as $k=>$v) {
+                    $aur[$k] = $v;
+                }
+            }
+        }
+      
+        // perms + groups.
+        $aur['perms']  = $this->getPerms();
+        $g = DB_DataObject::Factory('Group_Members');
+        $aur['groups']  = $g->listGroupMembership($this, 'name');
+        
+        $aur['passwd'] = '';
+        $aur['dailykey'] = '';
+        
+        
+        
+        return $aur;
+    }
+    
+    //   ----------PERMS------  ----------------
+    function getPerms() 
+    {
+         //DB_DataObject::debugLevel(1);
+        // find out all the groups they are a member of.. + Default..
+        
+        // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
+        
+        $g = DB_DataObject::Factory('Group_Rights');
+        if (!$g->count()) {
+            $g->genDefault();
+        }
+        
+        if ($this->id < 0) {
+            return $g->adminRights(); // system is not set up - so they get full rights.
+        }
+        //DB_DataObject::debugLevel(1);
+        $g = DB_DataObject::Factory('Group_Members');
+        $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
+        if (!$g->count()) {
+            // add the current user to the admin group..
+            $g = DB_DataObject::Factory('Groups');
+            if ($g->get('name', 'Administrators')) {
+                $gm = DB_DataObject::Factory('Group_Members');
+                $gm->group_id = $g->id;
+                $gm->user_id = $this->id;
+                $gm->insert();
+            }
+            
+        }
+        
+        // ------ STANDARD PERMISSION HANDLING.
+        
+        $g = DB_DataObject::Factory('Group_Members');
+        $grps = $g->listGroupMembership($this);
+       //var_dump($grps);
+        $isAdmin = $g->inAdmin;
+        //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
+        // the load all the perms for those groups, and add them all together..
+        // then load all those 
+        $g = DB_DataObject::Factory('Group_Rights');
+        $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
+        //echo '<PRE>';print_r($ret);
+        return $ret;
+         
+        
+    }
+    /**
+     *Basic group fetching - probably needs to filter by type eventually.
+     *
+     *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
+     */
+    
+    function groups($what=false)
+    {
+        $g = DB_DataObject::Factory('Group_Members');
+        $grps = $g->listGroupMembership($this);
+        $g = DB_DataObject::Factory('Groups');
+        $g->whereAddIn('id', $grps, 'int');
+        return $g->fetchAll($what);
+        
+    }
+    
+    function hasPerm($name, $lvl) 
+    {
+        static $pcache = array();
+        
+        if (!isset($pcache[$this->id])) {
+            $pcache[$this->id] = $this->getPerms();
+        }
+       // echo "<PRE>";print_r($pcache[$au->id]);
+       // var_dump($pcache[$au->id]);
+        if (empty($pcache[$this->id][$name])) {
+            return false;
+        }
+        
+        return strpos($pcache[$this->id][$name], $lvl) > -1;
+        
+    }    
+    
+    //  ------------ROO HOOKS------------------------------------
+    function applyFilters($q, $au, $roo)
+    {
+        //DB_DataObject::DebugLevel(1);
+        if (!empty($q['query']['person_not_internal'])) {
+            $this->whereAdd(" join_company_id_id.isOwner = 0 ");
+        }
+        if (!empty($q['query']['person_internal_only_all'])) {
+            
+            
+            // must be internal and not current user (need for distribution list)
+            // user has a projectdirectory entry and role is not blank.
+            //DB_DataObject::DebugLevel(1);
+            $pd = DB_DataObject::factory('ProjectDirectory');
+            $pd->whereAdd("role != ''");
+            $pd->selectAdd();
+            $pd->selectAdd('distinct(person_id) as person_id');
+            $roled = $pd->fetchAll('person_id');
+            $rs = $roled  ? "  OR
+                    {$this->tableName()}.id IN (".implode(',', $roled) . ") 
+                    " : '';
+            $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
+            
+        }
+        // -- for distribution
+        if (!empty($q['query']['person_internal_only'])) {
+            // must be internal and not current user (need for distribution list)
+            $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
+            
+            //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
+            //    ".id  != ".$au->id);
+            $this->whereAdd("Person.id != {$au->id}");
+        } 
+        
+        if (!empty($q['query']['comptype_or_company_id'])) {
+           // DB_DataObject::debugLevel(1);
+            $bits = explode(',', $q['query']['comptype_or_company_id']);
+            $id = (int) array_pop($bits);
+            $ct = $this->escape($bits[0]);
+            
+            $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
+            
+        }
+        
+        
+        // staff list..
+        if (!empty($q['query']['person_inactive'])) {
+           // DB_Dataobject::debugLevel(1);
+            $this->active = 1;
+        }
+        $tn_p = $this->tableName();
+        $tn_gm = DB_DataObject::Factory('Group_Members')->tableName();
+        $tn_g = DB_DataObject::Factory('Groups')->tableName();
+
+        ///---------------- Group views --------
+        if (!empty($q['query']['in_group'])) {
+            // DB_DataObject::debugLevel(1);
+            $ing = (int) $q['query']['in_group'];
+            if ($q['query']['in_group'] == -1) {
+             
+                // list all staff who are not in a group.
+                $this->whereAdd("Person.id NOT IN (
+                    SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
+                        $tn_g ON $tn_g.id = $tn_gm.group_id
+                        WHERE $tn_g.type = ".$q['query']['type']."
+                    )");
+                
+                
+            } else {
+                
+                $this->whereAdd("$tn_p.id IN (
+                    SELECT distinct(user_id) FROM $tn_gm
+                        WHERE group_id = $ing
+                    )");
+               }
+            
+        }
+        
+        if (!empty($q['query']['not_in_directory'])) { 
+            // it's a Person list..
+            // DB_DATaobjecT::debugLevel(1);
+            
+            // specific to project directory which is single comp. login
+            //
+            $owncomp = DB_DataObject::Factory('Companies');
+            $owncomp->get('comptype', 'OWNER');
+            if ($q['company_id'] == $owncomp->id) {
+                $this->active =1;
+            }
+            
+            
+
+            if ( $q['query']['not_in_directory'] > -1) {
+                $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
+                // can list current - so that it does not break!!!
+                $x->whereAdd("$tn_p.id NOT IN 
+                    ( SELECT distinct person_id FROM $tn_pd WHERE
+                        project_id = " . $q['query']['not_in_directory'] . " AND 
+                        company_id = " . $this->company_id . ')');
+            }
+        }
+        
+        
+        if (!empty($q['query']['project_member_of'])) {
+               // this is also a flag to return if they are a member..
+            //DB_DataObject::debugLevel(1);
+            $do = DB_DataObject::factory('ProjectDirectory');
+            $do->project_id = $q['query']['project_member_of'];
+            $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
+            $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
+            $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
+                
+                
+            if (!empty($q['query']['project_member_filter'])) {
+                $this->having('is_member !=0');
+            
+            }
+            
+        }
+        
+        
+        if (!empty($q['query']['search'])) {
+            $s = $this->escape($q['query']['search']);
+                    $this->whereAdd("
+                        $tn_p.name LIKE '%$s%'  OR
+                        $tn_p.email LIKE '%$s%'  OR
+                        $tn_p.role LIKE '%$s%'  OR
+                        $tn_p.remarks LIKE '%$s%' 
+                        
+                    ");
+        }
+        
+        //
+    }
+    function setFromRoo($ar, $roo)
+    {
+        $this->setFrom($ar);
+        if (!empty($ar['passwd1'])) {
+            $this->setPassword($ar['passwd1']);
+        }
+        
+        
+        if (    $this->id &&
+                ($this->email == $roo->old->email)&&
+                ($this->company_id == $roo->old->company_id)
+            ) {
+            return true;
+        }
+        if (empty($this->email)) {
+            return true;
+        }
+        $xx = DB_Dataobject::factory('Person');
+        $xx->setFrom(array(
+            'email' => $this->email,
+           // 'company_id' => $x->company_id
+        ));
+        
+        if ($xx->count()) {
+            return "Duplicate Email found";
+        }
+        return true;
+    }
+    /**
+     *
+     * before Delete - delete significant dependancies..
+     * this is called after checkPerm..
+     */
+    
+    function beforeDelete()
+    {
+        
+        $e = DB_DataObject::Factory('Events');
+        $e->whereAdd('person_id = ' . $this->id);
+        $e->delete(true);
+        
+        // anything else?  
+        
+    }
+    
+    
+    /***
+     * Check if the a user has access to modify this item.
+     * @param String $lvl Level (eg. Core.Projects)
+     * @param Pman_Core_DataObjects_Person $au The authenticated user.
+     * @param boolean $changes alllow changes???
+     *
+     * @return false if no access..
+     */
+    function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
+    {
+         
+       // do we have an empty system..
+        if ($au && $au->id == -1) {
+            return true;
+        }
+        
+        // determine if it's staff!!!
+         
+        if ($au->company()->comptype != 'OWNER') {
+            
+            // - can not change company!!!
+            if ($changes && 
+                isset($changes['company_id']) && 
+                $changes['company_id'] != $au->company_id) {
+                return false;
+            }
+            // can only set new emails..
+            if ($changes && 
+                    !empty($this->email) && 
+                    isset($changes['email']) && 
+                    $changes['email'] != $this->email) {
+                return false;
+            }
+            
+            // edit self... - what about other staff members...
+            
+            return $this->company_id == $au->company_id;
+        }
+         
+         
+        // yes, only owner company can mess with this...
+        $owncomp = DB_DataObject::Factory('Companies');
+        $owncomp->get('comptype', 'OWNER');
+        
+        $isStaff = ($this->company_id ==  $owncomp->id);
+        
+    
+        switch ($lvl) {
+            // extra case change passwod?
+            case 'P': //??? password
+                // standard perms -- for editing + if the user is dowing them selves..
+                $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
+                return $ret || $au->id == $this->id;
+            
+            default:                
+                return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
+        
+        }
+        return false;
+    }
+    function onInsert($req, $roo)  
+    {
+        
+        if ($roo->authUser->id < 0) {
+            $g = DB_DataObject::factory('Groups');
+            $g->type = 0;
+            $g->get('name', 'Administrators');
+            
+            $p = DB_DataObject::factory('Group_Members');
+            $p->group_id = $g->id;
+            $p->user_id = $this->id;     
+            if (!$p->count()) {
+                $p->insert();
+                $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
+            }
+            $this->login();
+        }
+        if (!empty($req['project_id_addto'])) {
+            $pd = DB_DataObject::factory('ProjectDirectory');
+            $pd->project_id = $req['project_id_addto'];
+            $pd->person_id = $this->id; 
+            $pd->ispm =0;
+            $pd->office_id = $this->office_id;
+            $pd->company_id = $this->company_id;
+            $pd->insert();
+        }
+        
+    }
+ }
diff --git a/DataObjects/core.sql b/DataObjects/core.sql
new file mode 100644 (file)
index 0000000..8a1540e
--- /dev/null
@@ -0,0 +1,380 @@
+
+CREATE TABLE Companies (
+  id int(11)  NOT NULL auto_increment,
+  PRIMARY KEY   (id)
+);
+
+
+ALTER TABLE Companies ADD COLUMN    code varchar(32)  NOT NULL DEFAULT '';;
+ALTER TABLE Companies ADD COLUMN    name varchar(128)  default NULL ;
+ALTER TABLE Companies ADD COLUMN    remarks text ;
+ALTER TABLE Companies ADD COLUMN    owner_id int(11) NOT NULL DEFAULT 0 ;
+ALTER TABLE Companies ADD COLUMN    address text ;
+ALTER TABLE Companies ADD COLUMN    tel varchar(32)  default NULL;
+ALTER TABLE Companies ADD COLUMN    fax varchar(32)  default NULL;
+ALTER TABLE Companies ADD COLUMN    email varchar(128)  default NULL;
+ALTER TABLE Companies ADD COLUMN    isOwner int(11) default NULL;
+ALTER TABLE Companies ADD COLUMN    logo_id INT(11)  NOT NULL DEFAULT 0;;
+ALTER TABLE Companies ADD COLUMN    background_color varchar(8)  NOT NULL;
+ALTER TABLE Companies ADD COLUMN    comptype varchar(8)  NOT NULL DEFAULT '';
+ALTER TABLE Companies ADD COLUMN    url varchar(254)  NOT NULL DEFAULT '';
+ALTER TABLE Companies ADD COLUMN    main_office_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE Companies ADD COLUMN    created_by int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE Companies ADD COLUMN    created_dt datetime  NOT NULL;
+ALTER TABLE Companies ADD COLUMN    updated_by int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE Companies ADD COLUMN    updated_dt datetime  NOT NULL;
+ALTER TABLE Companies ADD COLUMN    passwd varchar(64) NOT NULL DEFAULT '';
+ALTER TABLE Companies ADD COLUMN    dispatch_port varchar(255) NOT NULL DEFAULT '';
+ALTER TABLE Companies ADD COLUMN    province varchar(255) NOT NULL DEFAULT '';
+ALTER TABLE Companies ADD COLUMN    country varchar(4) NOT NULL DEFAULT '';
+
+
+ALTER TABLE Companies CHANGE COLUMN isOwner isOwner int(11);
+#postres
+ALTER TABLE Companies ALTER isOwner TYPE int(11);
+ALTER TABLE Companies ALTER owner_id SET DEFAULT 0;
+ALTER TABLE Companies ALTER url SET DEFAULT '';
+
+
+ALTER TABLE Companies ADD INDEX name_lookup (name);
+
+
+UPDATE Companies set comptype='OWNER' where isOwner=1;
+
+#// core comapy types - use core enums (Company Type)
+DROP TABLE core_company_type;
+
+CREATE TABLE Events (
+  id int(11) NOT NULL auto_increment,
+  
+  PRIMARY KEY  (id)
+) ;
+
+
+
+ALTER TABLE Events ADD COLUMN   person_name varchar(128)  default NULL;
+
+ALTER TABLE Events ADD COLUMN   event_when DATETIME default NULL;
+ALTER TABLE Events ADD COLUMN   action varchar(32)  default NULL;
+ALTER TABLE Events ADD COLUMN   ipaddr varchar(16)  default NULL;
+ALTER TABLE Events ADD COLUMN   on_id int(11) default NULL;
+ALTER TABLE Events ADD COLUMN   on_table varchar(64)  default NULL;
+ALTER TABLE Events ADD COLUMN   person_id int(11) default NULL;
+ALTER TABLE Events ADD COLUMN   remarks text ;
+
+#very old code..
+ALTER TABLE Events CHANGE COLUMN EventID id INT(11) AUTO_INCREMENT NOT NULL;
+
+# this are for pre-postgres support code..
+ALTER TABLE Events CHANGE COLUMN User person_name VARCHAR(128);
+ALTER TABLE Events RENAME COLUMN User TO person_name;
+ALTER TABLE Events CHANGE COLUMN Date event_when DATETIME ;
+ALTER TABLE Events CHANGE COLUMN Event action VARCHAR(32);
+ALTER TABLE Events CHANGE COLUMN Host ipaddr VARCHAR(16);
+ALTER TABLE Events CHANGE COLUMN ItemID on_id INT(11);
+ALTER TABLE Events CHANGE COLUMN Container on_table VARCHAR(64);
+
+
+ALTER TABLE Events ADD INDEX lookup (on_id, on_table, person_id, event_when);
+
+ALTER TABLE Events ADD INDEX lookupf (on_id, action, on_table, person_id, event_when);
+
+
+
+
+CREATE TABLE  core_event_audit  (
+    id int(11)  NOT NULL AUTO_INCREMENT,
+    PRIMARY KEY (id)
+);
+
+ALTER TABLE core_event_audit ADD COLUMN   event_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE core_event_audit ADD COLUMN       name varchar(128)  NOT NULL DEFAULT '';
+ALTER TABLE core_event_audit ADD COLUMN       old_audit_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE core_event_audit ADD COLUMN       newvalue BLOB  NOT NULL DEFAULT '';
+ALTER TABLE core_event_audit ADD   INDEX lookup(event_id, name, old_audit_id);
+
+CREATE TABLE  Group_Members  (
+    id int(11)  NOT NULL AUTO_INCREMENT,
+    PRIMARY KEY (id)
+);
+ALTER TABLE Group_Members ADD COLUMN  group_id int(11) default NULL;
+ALTER TABLE Group_Members ADD COLUMN   user_id int(11) NOT NULL default 0;
+
+CREATE TABLE  Group_Rights  (
+    id int(11)  NOT NULL AUTO_INCREMENT,
+    PRIMARY KEY (id)
+);
+ALTER TABLE Group_Rights ADD COLUMN    rightname varchar(64)  NOT NULL DEFAULT '';
+ALTER TABLE Group_Rights ADD COLUMN     group_id int(11) NOT NULL DEFAULT 0;
+ALTER TABLE Group_Rights ADD COLUMN   accessmask varchar(10)  NOT NULL DEFAULT '';
+
+#old mysql.
+ALTER TABLE Group_Rights CHANGE COLUMN AccessMask accessmask varchar(10)  NOT NULL DEFAULT '';
+
+
+
+
+CREATE TABLE Groups (
+  id int(11) NOT NULL auto_increment,  
+  PRIMARY KEY   (id)
+);
+
+ALTER TABLE Groups ADD COLUMN name varchar(64)  NOT NULL DEFAULT '';
+ALTER TABLE Groups ADD COLUMN   type int(11) default NULL ;
+ALTER TABLE Groups ADD COLUMN leader int(11)  NOT NULL default 0;
+#old mysql..
+ALTER TABLE Groups CHANGE COLUMN type type int(11) default 0;
+
+
+
+
+
+CREATE TABLE Office (
+  id int(11) NOT NULL auto_increment,
+  PRIMARY KEY  (id)
+);
+
+
+ALTER TABLE Office ADD COLUMN  company_id int(11) NOT NULL default '0';
+ALTER TABLE Office ADD COLUMN    name varchar(64)  NOT NULL  DEFAULT '';
+ALTER TABLE Office ADD COLUMN    address text ;
+ALTER TABLE Office ADD COLUMN    phone varchar(32)  NOT NULL  DEFAULT '';
+ALTER TABLE Office ADD COLUMN    fax varchar(32)  NOT NULL  DEFAULT '';
+ALTER TABLE Office ADD COLUMN    email varchar(128)  NOT NULL  DEFAULT '';
+ALTER TABLE Office ADD COLUMN    role varchar(32)  NOT NULL  DEFAULT '';
+
+
+CREATE TABLE Person (
+  id int(11) NOT NULL auto_increment,
+  PRIMARY KEY  (id)
+) ;
+
+ALTER TABLE Person ADD COLUMN   office_id int(11) default '0';
+ALTER TABLE Person ADD COLUMN   name varchar(128)  NOT NULL  DEFAULT '';
+ALTER TABLE Person ADD COLUMN   phone varchar(32)  NOT NULL  DEFAULT '';
+ALTER TABLE Person ADD COLUMN   fax varchar(32)  NOT NULL DEFAULT '';
+ALTER TABLE Person ADD COLUMN   email varchar(128)  NOT NULL DEFAULT '';
+ALTER TABLE Person ADD COLUMN   company_id int(11) default '0';
+ALTER TABLE Person ADD COLUMN   role varchar(254)  NOT NULL DEFAULT '';
+ALTER TABLE Person ADD COLUMN   active int(11) NOT NULL  default 1;
+ALTER TABLE Person ADD COLUMN   remarks text;
+ALTER TABLE Person ADD COLUMN   passwd varchar(64) NOT NULL  DEFAULT '';
+ALTER TABLE Person ADD COLUMN   owner_id int(11) NOT NULL DEFAULT 0;
+ALTER TABLE Person ADD COLUMN   lang varchar(8) default 'en';
+ALTER TABLE Person ADD COLUMN   no_reset_sent int(11) default '0';
+
+ALTER TABLE Person ADD COLUMN   action_type VARCHAR(32) DEFAULT '';
+ALTER TABLE Person ADD COLUMN   project_id int(11) default 0;
+ALTER TABLE Person ADD COLUMN   deleted_by INT(11) NOT NULL default 0 ;
+ALTER TABLE Person ADD COLUMN   deleted_dt DATETIME ;
+
+# old mysql
+alter table Person change column active active int(11) NOT NULL DEFAULT 1 ;
+alter table Person change role role varchar(254) NOT NULL DEFAULT '';
+
+
+
+
+
+CREATE TABLE Projects (
+  id int(11) NOT NULL auto_increment,
+  PRIMARY KEY  (id)
+  
+) ;
+
+
+
+ALTER TABLE  Projects  ADD COLUMN name varchar(254)  NOT NULL  DEFAULT '';
+ALTER TABLE  Projects  ADD COLUMN   remarks text ;
+ALTER TABLE  Projects  ADD COLUMN   owner_id int(11) default NULL;
+ALTER TABLE  Projects  ADD COLUMN   code varchar(32)  NOT NULL  DEFAULT '';
+ALTER TABLE  Projects  ADD COLUMN   active int(11) default '1';
+ALTER TABLE  Projects  ADD COLUMN   type varchar(1)  NOT NULL default 'P';
+ALTER TABLE  Projects  ADD COLUMN   client_id int(11) NOT NULL default '0';
+ALTER TABLE  Projects  ADD COLUMN   team_id int(11) NOT NULL default '0';
+ALTER TABLE  Projects  ADD COLUMN file_location varchar(254)    NOT NULL default '';
+ALTER TABLE  Projects  ADD COLUMN open_date date default NULL;
+ALTER TABLE  Projects  ADD COLUMN open_by int(11) NOT NULL default '0';
+
+
+# these should be removed, as they are code specific..
+ALTER TABLE Projects ADD COLUMN countries varchar(128)  NOT NULL DEFAULT '';
+ALTER TABLE Projects  ADD COLUMN languages varchar(128)  NOT NULL DEFAULT '';
+ALTER TABLE  Projects ADD COLUMN agency_id int(11)  NOT NULL DEFAULT 0 ;
+
+ALTER TABLE Projects ADD INDEX plookup (code);
+
+#-- we duplicate office_id and company_id here...
+#-- not sure if we should keep doing that in the new design...
+#-- we should improve our links code to handle this..
+
+
+CREATE TABLE ProjectDirectory (
+  id int(11) NOT NULL auto_increment,
+  PRIMARY KEY  (id)
+) ;
+
+ALTER TABLE  ProjectDirectory ADD COLUMN   project_id int(11) NOT NULL DEFAULT 0;
+ALTER TABLE  ProjectDirectory ADD COLUMN   person_id int(11) NOT NULL DEFAULT 0;
+ALTER TABLE  ProjectDirectory ADD COLUMN   ispm int(11) NOT NULL DEFAULT 0;
+ALTER TABLE  ProjectDirectory ADD COLUMN   role varchar(16) NOT NULL DEFAULT '';
+
+ALTER TABLE ProjectDirectory ADD INDEX plookup (project_id,person_id, ispm, role);
+
+
+CREATE TABLE   Images (
+  id int(11) NOT NULL auto_increment,
+  PRIMARY KEY  (id)
+);
+
+ALTER TABLE Images    ADD COLUMN   filename varchar(255) NOT NULL default '';
+ALTER TABLE Images    ADD COLUMN   ontable varchar(32) NOT NULL default '';
+ALTER TABLE Images    ADD COLUMN   onid int(11) NOT NULL default '0';
+ALTER TABLE Images    ADD COLUMN   mimetype varchar(64) NOT NULL default '';
+ALTER TABLE Images    ADD COLUMN   width int(11) NOT NULL default '0';
+ALTER TABLE Images    ADD COLUMN   height int(11) NOT NULL default '0';
+ALTER TABLE Images    ADD COLUMN   filesize int(11) NOT NULL default '0';
+ALTER TABLE Images    ADD COLUMN   displayorder int(11) NOT NULL default '0';
+ALTER TABLE Images    ADD COLUMN   language varchar(6) NOT NULL default 'en';
+ALTER TABLE Images    ADD COLUMN   parent_image_id int(11) NOT NULL default '0';
+
+ALTER TABLE  Images ADD COLUMN created datetime ;
+ALTER TABLE  Images ADD COLUMN imgtype VARCHAR(32) DEFAULT '' NOT NULL;
+ALTER TABLE  Images ADD COLUMN linkurl VARCHAR(254) DEFAULT '' NOT NULL;
+ALTER TABLE  Images ADD COLUMN descript TEXT DEFAULT '' NOT NULL;
+ALTER TABLE  Images ADD COLUMN title VARCHAR(128) DEFAULT '' NOT NULL;
+
+
+ALTER TABLE Images ADD INDEX lookup(ontable, onid);
+
+
+#// old core image type - merged into enum.
+DROP TABLE core_image_type;
+
+
+CREATE TABLE  i18n (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+  
+);
+
+ALTER TABLE  i18n ADD COLUMN   ltype varchar(1)  NOT NULL DEFAULT '';
+  ALTER TABLE  i18n ADD COLUMN   lkey varchar(8)  NOT NULL DEFAULT '';
+  ALTER TABLE  i18n ADD COLUMN   inlang varchar(8)  NOT NULL DEFAULT '';
+  ALTER TABLE  i18n ADD COLUMN   lval varchar(64)  NOT NULL DEFAULT '';
+  
+ALTER TABLE i18n ADD INDEX lookup (ltype, lkey, inlang);
+
+                       
+        
+    
+CREATE TABLE  core_locking (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+);
+ALTER TABLE  core_locking ADD COLUMN   on_table varchar(64)  NOT NULL DEFAULT '';
+ALTER TABLE  core_locking ADD COLUMN    on_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE  core_locking ADD COLUMN  person_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE  core_locking ADD COLUMN  created datetime ;
+
+alter table  core_locking ADD  INDEX lookup(on_table, on_id, person_id, created);
+# -- oops... - wrong name of pid.
+alter table  core_locking change column `int` id int(11) auto_increment not null;
+
+# -- a generic enumeraction
+
+CREATE TABLE   core_enum (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+);
+alter table  core_enum ADD COLUMN etype varchar(32)  NOT NULL DEFAULT '';
+alter table  core_enum ADD COLUMN  name varchar(255)  NOT NULL DEFAULT '';
+alter table  core_enum ADD COLUMN   active int(2)  NOT NULL DEFAULT 1;
+alter table  core_enum ADD COLUMN  seqid int(11)  NOT NULL DEFAULT 0;
+alter table  core_enum ADD COLUMN  seqmax int(11)  NOT NULL DEFAULT 0;
+
+alter table  core_enum ADD  INDEX lookup(seqid, active, name, etype);
+
+
+
+CREATE TABLE  translations (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+);
+
+alter table  translations ADD COLUMN    module varchar(64)  NOT NULL DEFAULT '';
+alter table  translations ADD COLUMN    tfile varchar(128) NOT NULL DEFAULT '';
+alter table  translations ADD COLUMN    tlang varchar(8)  NOT NULL DEFAULT '';
+alter table  translations ADD COLUMN    tkey varchar(32)  NOT NULL DEFAULT '';
+alter table  translations ADD COLUMN    tval longtext ;
+
+
+ALTER TABLE translations ADD INDEX qlookup (module, tfile, tlang, tkey);
+
+
+# - used to trigger emails about changes to items being watched.
+
+CREATE TABLE core_watch (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+) ;
+
+
+alter table  core_watch ADD COLUMN    ontable varchar(128) NOT NULL DEFAULT '';
+alter table  core_watch ADD COLUMN   onid int(11) NOT NULL DEFAULT 0;
+alter table  core_watch ADD COLUMN   person_id int(11) NOT NULL DEFAULT 0;
+alter table  core_watch ADD COLUMN   event varchar(128) NOT NULL DEFAULT '';
+alter table  core_watch ADD COLUMN   medium varchar(64) NOT NULL DEFAULT '';
+alter table  core_watch ADD COLUMN  active int(11) NOT NULL DEFAULT '1';
+
+ALTER TABLE core_watch ADD INDEX qlookup (ontable,onid,person_id,event,medium);
+
+
+
+
+CREATE TABLE  core_notify  (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (id)
+);
+
+ALTER TABLE core_notify ADD COLUMN   act_when DATETIME ;
+ALTER TABLE core_notify ADD COLUMN    act_start DATETIME ;
+ALTER TABLE core_notify ADD COLUMN  onid int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD COLUMN  ontable varchar(128)  NOT NULL DEFAULT '';
+ALTER TABLE core_notify ADD COLUMN  person_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD COLUMN  msgid varchar(128)  NOT NULL  DEFAULT '';
+
+ALTER TABLE core_notify ADD COLUMN  sent DATETIME ;
+ALTER TABLE core_notify ADD COLUMN  event_id int(11)  NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD COLUMN  watch_id INT(11) NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD COLUMN  trigger_person_id INT(11) NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD COLUMN  trigger_event_id INT(11) NOT NULL DEFAULT 0;
+ALTER TABLE core_notify ADD   INDEX lookup(act_when, msgid);
+ALTER TABLE core_notify ADD COLUMN  to_email varchar(255)  NOT NULL  DEFAULT '';
+ALTER TABLE core_notify ADD   INDEX lookup_a(onid, ontable, person_id, act_when, msgid, to_email);
+
+#old mysql..
+ALTER TABLE core_notify CHANGE COLUMN bounced event_id INT(11) NOT NULL DEFAULT 0;
+  
+
+
+
+# - used by email / tracker to handle alises - we have to be carefull adding to this table...
+
+CREATE TABLE core_person_alias (
+  id int(11)  NOT NULL AUTO_INCREMENT,
+
+  PRIMARY KEY (id)
+) ;
+ALTER TABLE core_person_alias ADD COLUMN   person_id varchar(128) DEFAULT NULL;
+ALTER TABLE core_person_alias ADD COLUMN  alias varchar(254) NOT NULL DEFAULT '';
+  
+ALTER TABLE core_person_alias ADD INDEX alias (alias);