DataObjects/Person.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Person extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Person';                          // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $email;                           // string(128)  not_null
15     public $alt_email;
16     
17     public $company_id;                      // int(11)  
18     public $office_id;                       // int(11)  
19     public $name;                            // string(128)  not_null
20     public $firstname;                            // string(128)  not_null
21     public $lastname;                            // string(128)  not_null
22     public $phone;                           // string(32)  not_null
23     public $fax;                             // string(32)  not_null
24     
25     public $role;                            // string(32)  not_null
26     public $remarks;                         // blob(65535)  not_null blob
27     public $passwd;                          // string(64)  not_null
28     public $owner_id;                        // int(11)  not_null
29     public $lang;                            // string(8)  
30     public $no_reset_sent;                   // int(11)  
31     public $action_type;                     // string(32)  
32     public $project_id;                      // int(11)
33
34     
35     public $active;                          // int(11)  not_null
36     public $deleted_by;                      // int(11)  not_null
37     public $deleted_dt;                      // datetime(19)  binary
38
39
40     public $name_facebook; // VARCHAR(128) NULL;
41     public $url_blog; // VARCHAR(256) NULL ;
42     public $url_twitter; // VARCHAR(256) NULL ;
43     public $url_linkedin; // VARCHAR(256) NULL ;
44     
45     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
46     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
47     
48     /* the code above is auto generated do not remove the tag below */
49     ###END_AUTOCODE
50     
51     function owner()
52     {
53         $p = DB_DataObject::Factory('Person');
54         $p->get($this->owner_id);
55         return $p;
56     }
57     
58     /**
59      *
60      *
61      *
62      *
63      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
64      *
65      *
66      *
67      *  
68      */
69     function buildMail($templateFile, $args)
70     {
71           
72         $args = (array) $args;
73         $content  = clone($this);
74         
75         foreach((array)$args as $k=>$v) {
76             $content->$k = $v;
77         }
78         
79         $ff = HTML_FlexyFramework::get();
80         
81         
82         //?? is this really the place for this???
83         if (
84                 !$ff->cli && 
85                 empty($args['no_auth']) &&
86                 !in_array($templateFile, array(
87                     // templates that can be sent without authentication.
88                      'password_reset' ,
89                      'password_welcome'
90                  ))
91             ) {
92             
93             $content->authUser = $this->getAuthUser();
94             if (!$content->authUser) {
95                 return PEAR::raiseError("Not authenticated");
96             }
97         }
98         
99         // should handle x-forwarded...
100         
101         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
102             $_SERVER["HTTP_HOST"] :
103             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
104             
105         /* use the regex compiler, as it doesnt parse <tags */
106         
107         $tops = array(
108             'compiler'    => 'Flexy',
109             'nonHTML' => true,
110             'filters' => array('SimpleTags','Mail'),
111             //     'debug'=>1,
112         );
113         
114         
115         
116         if (!empty($args['templateDir'])) {
117             $tops['templateDir'] = $args['templateDir'];
118         }
119         
120         
121         
122         require_once 'HTML/Template/Flexy.php';
123         $template = new HTML_Template_Flexy( $tops );
124         $template->compile("mail/$templateFile.txt");
125         
126         /* use variables from this object to ouput data. */
127         $mailtext = $template->bufferedOutputObject($content);
128         
129         $htmlbody = false;
130         // if a html file with the same name exists, use that as the body
131         // I've no idea where this code went, it was here before..
132         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
133             $tops['nonHTML'] = false;
134             $template = new HTML_Template_Flexy( $tops );
135             $template->compile("mail/$templateFile.html");
136             $htmlbody = $template->bufferedOutputObject($content);
137             
138         }
139         
140         
141         
142         //echo "<PRE>";print_R($mailtext);
143         //print_R($mailtext);exit;
144         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
145         require_once 'Mail/mimeDecode.php';
146         require_once 'Mail.php';
147         
148         $decoder = new Mail_mimeDecode($mailtext);
149         $parts = $decoder->getSendArray();
150         
151         if (PEAR::isError($parts)) {
152             return $parts;
153             //echo "PROBLEM: {$parts->message}";
154             //exit;
155         } 
156         list($recipents,$headers,$body) = $parts;
157         $recipents = array($this->email);
158         if (!empty($content->bcc) && is_array($content->bcc)) {
159             $recipents =array_merge($recipents, $content->bcc);
160         }
161         $headers['Date'] = date('r');
162         
163         if ($htmlbody !== false) {
164             require_once 'Mail/mime.php';
165             $mime = new Mail_mime(array('eol' => "\n"));
166             $mime->setTXTBody($body);
167             $mime->setHTMLBody($htmlbody);
168             // I think there might be code in mediaoutreach toEmail somewhere
169             // h embeds images here..
170             $body = $mime->get();
171             $headers = $mime->headers($headers);
172             
173         }
174         
175          
176         
177         return array(
178             'recipients' => $recipents,
179             'headers'    => $headers,
180             'body'      => $body
181         );
182         
183         
184     }
185     
186     
187     /**
188      * send a template
189      * - user must be authenticate or args[no_auth] = true
190      *   or template = password_[reset|welcome]
191      * 
192      */
193     function sendTemplate($templateFile, $args)
194     {
195         
196         $ar = $this->buildMail($templateFile, $args);
197       
198         
199         //print_r($recipents);exit;
200         $mailOptions = PEAR::getStaticProperty('Mail','options');
201         $mail = Mail::factory("SMTP",$mailOptions);
202         
203         if (PEAR::isError($mail)) {
204             return $mail;
205         } 
206         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
207         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
208         error_reporting($oe);
209        
210         return $ret;
211     
212     }
213     
214   
215     
216     
217     function getEmailFrom()
218     {
219         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
220     }
221     function toEventString() 
222     {
223         return empty($this->name) ? $this->email : $this->name;
224     } 
225     function verifyAuth()
226     { 
227         $ff= HTML_FlexyFramework::get();
228         if (!empty($ff->Pman['auth_comptype']) &&
229             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
230            ){
231             $ff->page->jerr("Login not permited to outside companies");
232         }
233         return true;
234         
235     }    
236    
237    
238     //   ---------------- authentication / passwords and keys stuff  ----------------
239     function isAuth()
240     {
241         $db = $this->getDatabaseConnection();
242         // we combine db + project names,
243         // otherwise if projects use different 'auth' objects
244         // then we get unserialize issues.
245         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
246         
247         
248         @session_start();
249          
250         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
251             // in session...
252             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
253             
254             $u = DB_DataObject::factory('Person');
255             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
256                 die("verify");
257                 $u->verifyAuth();
258                 
259                 return true;
260             }
261             
262             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
263             
264         }
265         // local auth - 
266         $u = DB_DataObject::factory('Person');
267         $ff = HTML_FlexyFramework::get();
268         if (!empty($ff->Pman['local_autoauth']) && 
269             (!empty($_SERVER['SERVER_ADDR'])) &&
270             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
271             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
272             $u->get('email', $ff->Pman['local_autoauth'])
273         ) {
274             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
275             return true;
276         }
277            
278         // http basic auth..
279         $u = DB_DataObject::factory('Person');
280
281         if (!empty($_SERVER['PHP_AUTH_USER']) 
282             &&
283             !empty($_SERVER['PHP_AUTH_PW'])
284             &&
285             $u->get('email', $_SERVER['PHP_AUTH_USER'])
286             &&
287             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
288            ) {
289             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
290             return true; 
291         }
292         
293         if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
294             return false;
295         }
296         
297         // not in session or not matched...
298         $u = DB_DataObject::factory('Person');
299         $u->whereAdd(' LENGTH(passwd) > 0');
300         $n = $u->count();
301         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
302         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
303         if ($error) {
304             die($error->toString()); // not really a good thing to do...
305         }
306         if (!$n){ // authenticated as there are no users in the system...
307             return true;
308         }
309         
310         return false;
311         
312     }
313     function getAuthUser()
314     {
315         if (!$this->isAuth()) {
316             return false;
317         }
318         $db = $this->getDatabaseConnection();
319         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
320         
321         
322         
323         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
324             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
325             
326             $u = DB_DataObject::factory('Person');
327             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
328                 return clone($u);
329             }
330              
331         }
332         
333         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
334             $u = DB_DataObject::factory('Person');
335             $u->whereAdd(' LENGTH(passwd) > 0');
336              $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
337         }
338                 
339              
340         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
341             
342             // fake person - open system..
343             //$ce = DB_DataObject::factory('core_enum');
344             //$ce->initEnums();
345             
346             
347             $u = DB_DataObject::factory('Person');
348             $u->id = -1;
349             return $u;
350             
351         }
352         return false;
353     }     
354     function login()
355     {
356         $this->isAuth(); // force session start..
357         $this->verifyAuth();
358         $db = $this->getDatabaseConnection();
359         
360         
361         // open up iptables at login..
362         $dbname = $this->database();
363         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
364          
365         // refresh admin group if we are logged in as one..
366         //DB_DataObject::debugLevel(1);
367         $g = DB_DataObject::factory('Groups');
368         $g->type = 0;
369         $g->get('name', 'Administrators');
370         $gm = DB_DataObject::Factory('group_members');
371         if (in_array($g->id,$gm->listGroupMembership($this))) {
372             // refresh admin groups.
373             $gr = DB_DataObject::Factory('group_rights');
374             $gr->applyDefs($g, 0);
375         }
376              
377         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
378         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
379         
380     }
381     function logout()
382     {
383         $this->isAuth(); // force session start..
384          $db = $this->getDatabaseConnection();
385         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
386         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
387         
388     }    
389     function genPassKey ($t) 
390     {
391         return md5($this->email . $t. $this->passwd);
392     }
393     function simpleAuthKey($m = 0)
394     {
395         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
396         
397         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
398     } 
399     function checkPassword($val)
400     {
401         
402         if (substr($this->passwd,0,1) == '$') {
403             return crypt($val,$this->passwd) == $this->passwd ;
404         }
405         // old style md5 passwords...- cant be used with courier....
406         return md5($val) == $this->passwd;
407     }
408     function setPassword($value) 
409     {
410         $salt='';
411         while(strlen($salt)<9) {
412             $salt.=chr(rand(64,126));
413             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
414         }
415         $this->passwd = crypt($value, '$1$'. $salt. '$');
416        
417        
418     }      
419     
420     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
421     {
422         require_once 'Text/Password.php';
423         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
424         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
425         $this->setPassword($this->rawPasswd);
426         return $this->rawPasswd;
427     }
428     
429     function company()
430     {
431         $x = DB_DataObject::factory('Companies');
432         $x->autoJoin();
433         $x->get($this->company_id);
434         return $x;
435     }
436     function loadCompany()
437     {
438         $this->company = $this->company();
439     }
440     
441     function active()
442     { 
443         return $this->active;
444     }
445     function authUserName($n) // set username prior to acheck user exists query.
446     {
447         
448         $this->whereAdd('LENGTH(passwd) > 1'); 
449         $this->email = $n;
450     }
451     function lang($val)
452     {
453         if ($val == $this->lang) {
454             return;
455         }
456         $uu = clone($this);
457         $this->lang = $val;
458         $this->update($uu);
459
460     }
461             
462     
463     function authUserArray()
464     {
465         
466         $aur = $this->toArray();
467         
468         if ($this->id < 1) {
469             return $aur;
470         }
471         
472         
473         //DB_DataObject::debugLevel(1);
474         $c = DB_Dataobject::factory('Companies');
475         $im = DB_Dataobject::factory('Images');
476         $c->joinAdd($im, 'LEFT');
477         $c->selectAdd();
478         $c->selectAs($c, 'company_id_%s');
479         $c->selectAs($im, 'company_id_logo_id_%s');
480         $c->id = $this->company_id;
481         $c->limit(1);
482         $c->find(true);
483         
484         $aur = array_merge( $c->toArray(),$aur);
485         
486         if (empty($c->company_id_logo_id_id))  {
487                  
488             $im = DB_Dataobject::factory('Images');
489             $im->ontable = 'Companies';
490             $im->onid = $c->id;
491             $im->imgtype = 'LOGO';
492             $im->limit(1);
493             $im->selectAdd();
494             $im->selectAs($im,  'company_id_logo_id_%s');
495             if ($im->find(true)) {
496                     
497                 foreach($im->toArray() as $k=>$v) {
498                     $aur[$k] = $v;
499                 }
500             }
501         }
502       
503         // perms + groups.
504         $aur['perms']  = $this->getPerms();
505         $g = DB_DataObject::Factory('group_members');
506         $aur['groups']  = $g->listGroupMembership($this, 'name');
507         
508         $aur['passwd'] = '';
509         $aur['dailykey'] = '';
510         
511         
512         
513         return $aur;
514     }
515     
516     //   ----------PERMS------  ----------------
517     function getPerms() 
518     {
519          //DB_DataObject::debugLevel(1);
520         // find out all the groups they are a member of.. + Default..
521         
522         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
523         
524         $g = DB_DataObject::Factory('group_rights');
525         if (!$g->count()) {
526             $g->genDefault();
527         }
528         
529         if ($this->id < 0) {
530             return $g->adminRights(); // system is not set up - so they get full rights.
531         }
532         //DB_DataObject::debugLevel(1);
533         $g = DB_DataObject::Factory('group_members');
534         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
535         if (!$g->count()) {
536             // add the current user to the admin group..
537             $g = DB_DataObject::Factory('Groups');
538             if ($g->get('name', 'Administrators')) {
539                 $gm = DB_DataObject::Factory('group_members');
540                 $gm->group_id = $g->id;
541                 $gm->user_id = $this->id;
542                 $gm->insert();
543             }
544             
545         }
546         
547         // ------ STANDARD PERMISSION HANDLING.
548         $isOwner = $this->company()->comptype == 'OWNER';
549         $g = DB_DataObject::Factory('group_members');
550         $grps = $g->listGroupMembership($this);
551        //var_dump($grps);
552         $isAdmin = $g->inAdmin;
553         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
554         // the load all the perms for those groups, and add them all together..
555         // then load all those 
556         $g = DB_DataObject::Factory('group_rights');
557         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
558         //echo '<PRE>';print_r($ret);
559         return $ret;
560          
561         
562     }
563     /**
564      *Basic group fetching - probably needs to filter by type eventually.
565      *
566      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
567      */
568     
569     function groups($what=false)
570     {
571         $g = DB_DataObject::Factory('group_members');
572         $grps = $g->listGroupMembership($this);
573         $g = DB_DataObject::Factory('Groups');
574         $g->whereAddIn('id', $grps, 'int');
575         return $g->fetchAll($what);
576         
577     }
578     
579     
580     
581     function hasPerm($name, $lvl) 
582     {
583         static $pcache = array();
584         
585         if (!isset($pcache[$this->id])) {
586             $pcache[$this->id] = $this->getPerms();
587         }
588        // echo "<PRE>";print_r($pcache[$au->id]);
589        // var_dump($pcache[$au->id]);
590         if (empty($pcache[$this->id][$name])) {
591             return false;
592         }
593         
594         return strpos($pcache[$this->id][$name], $lvl) > -1;
595         
596     }    
597     
598     //  ------------ROO HOOKS------------------------------------
599     function applyFilters($q, $au, $roo)
600     {
601         //DB_DataObject::DebugLevel(1);
602         if (!empty($q['query']['person_not_internal'])) {
603             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
604         }
605         
606         
607         if (!empty($q['query']['person_internal_only_all'])) {
608             
609             
610             // must be internal and not current user (need for distribution list)
611             // user has a projectdirectory entry and role is not blank.
612             //DB_DataObject::DebugLevel(1);
613             $pd = DB_DataObject::factory('ProjectDirectory');
614             $pd->whereAdd("role != ''");
615             $pd->selectAdd();
616             $pd->selectAdd('distinct(person_id) as person_id');
617             $roled = $pd->fetchAll('person_id');
618             $rs = $roled  ? "  OR
619                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
620                     " : '';
621             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
622             
623         }
624         // -- for distribution
625         if (!empty($q['query']['person_internal_only'])) {
626             // must be internal and not current user (need for distribution list)
627             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
628             
629             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
630             //    ".id  != ".$au->id);
631             $this->whereAdd("Person.id != {$au->id}");
632         } 
633         
634         if (!empty($q['query']['comptype_or_company_id'])) {
635            // DB_DataObject::debugLevel(1);
636             $bits = explode(',', $q['query']['comptype_or_company_id']);
637             $id = (int) array_pop($bits);
638             $ct = $this->escape($bits[0]);
639             
640             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
641             
642         }
643         
644         
645         // staff list..
646         if (!empty($q['query']['person_inactive'])) {
647            // DB_Dataobject::debugLevel(1);
648             $this->active = 1;
649         }
650         $tn_p = $this->tableName();
651         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
652         $tn_g = DB_DataObject::Factory('Groups')->tableName();
653
654         ///---------------- Group views --------
655         if (!empty($q['query']['in_group'])) {
656             // DB_DataObject::debugLevel(1);
657             $ing = (int) $q['query']['in_group'];
658             if ($q['query']['in_group'] == -1) {
659              
660                 // list all staff who are not in a group.
661                 $this->whereAdd("Person.id NOT IN (
662                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
663                         $tn_g ON $tn_g.id = $tn_gm.group_id
664                         WHERE $tn_g.type = ".$q['query']['type']."
665                     )");
666                 
667                 
668             } else {
669                 
670                 $this->whereAdd("$tn_p.id IN (
671                     SELECT distinct(user_id) FROM $tn_gm
672                         WHERE group_id = $ing
673                     )");
674                }
675             
676         }
677         
678         if (!empty($q['query']['not_in_directory'])) { 
679             // it's a Person list..
680             // DB_DATaobjecT::debugLevel(1);
681             
682             // specific to project directory which is single comp. login
683             //
684             $owncomp = DB_DataObject::Factory('Companies');
685             $owncomp->get('comptype', 'OWNER');
686             if ($q['company_id'] == $owncomp->id) {
687                 $this->active =1;
688             }
689             
690             
691
692             if ( $q['query']['not_in_directory'] > -1) {
693                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
694                 // can list current - so that it does not break!!!
695                 $this->whereAdd("$tn_p.id NOT IN 
696                     ( SELECT distinct person_id FROM $tn_pd WHERE
697                         project_id = " . $q['query']['not_in_directory'] . " AND 
698                         company_id = " . $this->company_id . ')');
699             }
700         }
701            
702         if (!empty($q['query']['role'])) { 
703             // it's a Person list..
704             // DB_DATaobjecT::debugLevel(1);
705             
706             // specific to project directory which is single comp. login
707             //
708             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
709                 // can list current - so that it does not break!!!
710             $this->whereAdd("$tn_p.id IN 
711                     ( SELECT distinct person_id FROM $tn_pd WHERE
712                         role = '". $this->escape($q['query']['role']) ."'
713             )");
714         
715         }
716         
717         
718         if (!empty($q['query']['project_member_of'])) {
719                // this is also a flag to return if they are a member..
720             //DB_DataObject::debugLevel(1);
721             $do = DB_DataObject::factory('ProjectDirectory');
722             $do->project_id = $q['query']['project_member_of'];
723             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
724             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
725             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
726                 
727                 
728             if (!empty($q['query']['project_member_filter'])) {
729                 $this->having('is_member !=0');
730             
731             }
732             
733         }
734         
735         if (!empty($q['query']['search'])) {
736             
737             // use our magic search builder...
738             
739              require_once 'Text/SearchParser.php';
740             $x = new Text_SearchParser($q['query']['search']);
741             
742             $props = array(
743                     "$tn_p.name",
744                     "$tn_p.email",
745                     "$tn_p.role",
746                     "$tn_p.phone",
747                     "$tn_p.remarks",
748                     "join_company_id_id.name"
749             );
750             
751             $str =  $x->toSQL(array(
752                 'default' => $props,
753                 'map' => array(
754                     'company' => 'join_company_id_id.name',
755                     //'country' => 'Clipping.country',
756                     //  'media' => 'Clipping.media_name',
757                 ),
758                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
759
760             ));
761             
762             
763             $this->whereAdd($str); /*
764                         $tn_p.name LIKE '%$s%'  OR
765                         $tn_p.email LIKE '%$s%'  OR
766                         $tn_p.role LIKE '%$s%'  OR
767                         $tn_p.phone LIKE '%$s%' OR
768                         $tn_p.remarks LIKE '%$s%' 
769                         
770                     ");*/
771         }
772         
773         //
774     }
775     function setFromRoo($ar, $roo)
776     {
777         $this->setFrom($ar);
778         if (!empty($ar['passwd1'])) {
779             $this->setPassword($ar['passwd1']);
780         }
781         
782         
783         if (    $this->id &&
784                 ($this->email == $roo->old->email)&&
785                 ($this->company_id == $roo->old->company_id)
786             ) {
787             return true;
788         }
789         if (empty($this->email)) {
790             return true;
791         }
792         $xx = DB_Dataobject::factory('Person');
793         $xx->setFrom(array(
794             'email' => $this->email,
795            // 'company_id' => $x->company_id
796         ));
797         
798         if ($xx->count()) {
799             return "Duplicate Email found";
800         }
801         return true;
802     }
803     /**
804      *
805      * before Delete - delete significant dependancies..
806      * this is called after checkPerm..
807      */
808     
809     function beforeDelete()
810     {
811         
812         $e = DB_DataObject::Factory('Events');
813         $e->whereAdd('person_id = ' . $this->id);
814         $e->delete(true);
815         
816         // anything else?  
817         
818     }
819     
820     
821     /***
822      * Check if the a user has access to modify this item.
823      * @param String $lvl Level (eg. Core.Projects)
824      * @param Pman_Core_DataObjects_Person $au The authenticated user.
825      * @param boolean $changes alllow changes???
826      *
827      * @return false if no access..
828      */
829     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
830     {
831          
832        // do we have an empty system..
833         if ($au && $au->id == -1) {
834             return true;
835         }
836         
837         // determine if it's staff!!!
838          
839         if ($au->company()->comptype != 'OWNER') {
840             
841             // - can not change company!!!
842             if ($changes && 
843                 isset($changes['company_id']) && 
844                 $changes['company_id'] != $au->company_id) {
845                 return false;
846             }
847             // can only set new emails..
848             if ($changes && 
849                     !empty($this->email) && 
850                     isset($changes['email']) && 
851                     $changes['email'] != $this->email) {
852                 return false;
853             }
854             
855             // edit self... - what about other staff members...
856             
857             return $this->company_id == $au->company_id;
858         }
859          
860          
861         // yes, only owner company can mess with this...
862         $owncomp = DB_DataObject::Factory('Companies');
863         $owncomp->get('comptype', 'OWNER');
864         
865         $isStaff = ($this->company_id ==  $owncomp->id);
866         
867     
868         switch ($lvl) {
869             // extra case change passwod?
870             case 'P': //??? password
871                 // standard perms -- for editing + if the user is dowing them selves..
872                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
873                 return $ret || $au->id == $this->id;
874             
875             default:                
876                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
877         
878         }
879         return false;
880     }
881     function onInsert($req, $roo)  
882     {
883          
884         $p = DB_DataObject::factory('person');
885         if ($roo->authUser->id < 0 && $p->count() == 1) {
886             // this seems a bit risky...
887             
888             $g = DB_DataObject::factory('Groups');
889             $g->initGroups();
890             
891             $g->type = 0;
892             $g->get('name', 'Administrators');
893             
894             $p = DB_DataObject::factory('group_members');
895             $p->group_id = $g->id;
896             $p->user_id = $this->id;     
897             if (!$p->count()) {
898                 $p->insert();
899                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
900             }
901             $this->login();
902         }
903         if (!empty($req['project_id_addto'])) {
904             $pd = DB_DataObject::factory('ProjectDirectory');
905             $pd->project_id = $req['project_id_addto'];
906             $pd->person_id = $this->id; 
907             $pd->ispm =0;
908             $pd->office_id = $this->office_id;
909             $pd->company_id = $this->company_id;
910             $pd->insert();
911         }
912         
913     }
914     
915     function importFromArray($roo, $persons, $prefix)
916     {
917         if (!is_array($persons) || empty($persons)) {
918             $roo->jerr("error in the person data. - empty on not valid");
919         }
920         DB_DataObject::factory('groups')->initGroups();
921         
922         foreach($persons as $person){
923             $p = DB_DataObject::factory('person');
924             if($p->get('name', $person['name'])){
925                 continue;
926             }
927             $p->setFrom($person);
928             
929             $companies = DB_DataObject::factory('companies');
930             if(!$companies->get('comptype', 'OWNER')){
931                 $roo->jerr("Missing OWNER companies!");
932             }
933             $p->company_id = $companies->pid();
934             // strip the 'spaces etc.. make lowercase..
935             $name = strtolower(str_replace(' ', '', $person['name']));
936             $p->setPassword("$prefix$name");
937             $p->insert();
938             // set up groups
939             // if $person->groups is set.. then
940             // add this person to that group eg. groups : [ 'Administrator' ] 
941             if(!empty($person['groups'])){
942                 $groups = DB_DataObject::factory('groups');
943                 if(!$groups->get('name', $person['groups'])){
944                     $roo->jerr("Missing groups : {$person['groups']}");
945                 }
946                 $gm = DB_DataObject::factory('group_members');
947                 $gm->change($p, $groups, true);
948             }
949             
950             $p->onInsert(array(), $roo);
951         }
952     }
953  }