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