DataObjects/Core_watch.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->autoJoin();
288             $member->group_id = $group->id;
289             $member->whereAdd("
290                 join_user_id_id.id IS NOT NULL
291             ");
292             if($member->find(true)){
293                 $default_admin = DB_DataObject::factory('Person');
294                 if(!$default_admin->get($member->user_id)){
295                     $default_admin = false;
296                 }
297             }
298         }
299         
300          
301         $u = DB_DataObject::factory('Person');
302         $ff = HTML_FlexyFramework::get();
303         if (!empty($ff->Pman['local_autoauth']) && 
304             (!empty($_SERVER['SERVER_ADDR'])) &&
305             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
306             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
307             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
308         ) {
309             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
310             return true;
311         }
312            
313         // http basic auth..
314         $u = DB_DataObject::factory('Person');
315
316         if (!empty($_SERVER['PHP_AUTH_USER']) 
317             &&
318             !empty($_SERVER['PHP_AUTH_PW'])
319             &&
320             $u->get('email', $_SERVER['PHP_AUTH_USER'])
321             &&
322             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
323            ) {
324             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
325             return true; 
326         }
327         //var_dump(session_id());
328         //var_dump($_SESSION[__CLASS__]);
329         
330         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
331         //    return false;
332         //}
333         //die("got this far?");
334         // not in session or not matched...
335         $u = DB_DataObject::factory('Person');
336         $u->whereAdd(' LENGTH(passwd) > 0');
337         $n = $u->count();
338         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
339         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
340         if ($error) {
341             die($error->toString()); // not really a good thing to do...
342         }
343         if (!$n){ // authenticated as there are no users in the system...
344             return true;
345         }
346         
347         return false;
348         
349     }
350     function getAuthUser()
351     {
352         if (!$this->isAuth()) {
353             return false;
354         }
355         $db = $this->getDatabaseConnection();
356         
357         $ff= HTML_FlexyFramework::get();
358         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
359
360         
361         
362         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
363             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
364             
365             $u = DB_DataObject::factory('Person');
366             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
367                 return clone($u);
368             }
369             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
370         }
371         
372         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
373             $u = DB_DataObject::factory('Person');
374             $u->whereAdd(' LENGTH(passwd) > 0');
375             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
376         }
377                 
378              
379         if (isset(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] ) && $_SESSION[__CLASS__][$sesPrefix .'-empty']  < 1) {
380             
381             // fake person - open system..
382             //$ce = DB_DataObject::factory('core_enum');
383             //$ce->initEnums();
384             
385             
386             $u = DB_DataObject::factory('Person');
387             $u->id = -1;
388             
389             // if a company has been created fill that in in company_id_id
390             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
391             if ($c) {
392                 $u->company_id_id = $c->pid();
393                 $u->company_id = $c->pid();
394             }
395             
396             return $u;
397             
398         }
399         return false;
400     }     
401     function login()
402     {
403         $this->isAuth(); // force session start..
404         if (!$this->verifyAuth()) {
405             return false;
406         }
407         $db = $this->getDatabaseConnection();
408         
409         
410         // open up iptables at login..
411         $dbname = $this->database();
412         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
413          
414         // refresh admin group if we are logged in as one..
415         //DB_DataObject::debugLevel(1);
416         $g = DB_DataObject::factory('Groups');
417         $g->type = 0;
418         $g->get('name', 'Administrators');
419         $gm = DB_DataObject::Factory('group_members');
420         if (in_array($g->id,$gm->listGroupMembership($this))) {
421             // refresh admin groups.
422             $gr = DB_DataObject::Factory('group_rights');
423             $gr->applyDefs($g, 0);
424         }
425         $ff= HTML_FlexyFramework::get();
426         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
427
428
429         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
430         
431     }
432     function logout()
433     {
434         $this->isAuth(); // force session start..
435         $db = $this->getDatabaseConnection();
436         $ff= HTML_FlexyFramework::get();
437         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
438
439         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
440        
441         
442        
443         
444     }    
445     function genPassKey ($t) 
446     {
447         return md5($this->email . $t. $this->passwd);
448     }
449     function simpleAuthKey($m = 0)
450     {
451         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
452         
453         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
454     } 
455     function checkPassword($val)
456     {
457         
458         if (substr($this->passwd,0,1) == '$') {
459             return crypt($val,$this->passwd) == $this->passwd ;
460         }
461         // old style md5 passwords...- cant be used with courier....
462         return md5($val) == $this->passwd;
463     }
464     function setPassword($value) 
465     {
466         $salt='';
467         while(strlen($salt)<9) {
468             $salt.=chr(rand(64,126));
469             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
470         }
471         $this->passwd = crypt($value, '$1$'. $salt. '$');
472        
473        
474     }      
475     
476     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
477     {
478         require_once 'Text/Password.php';
479         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
480         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
481         $this->setPassword($this->rawPasswd);
482         return $this->rawPasswd;
483     }
484     
485     function company()
486     {
487         $x = DB_DataObject::factory('Companies');
488         $x->autoJoin();
489         $x->get($this->company_id);
490         return $x;
491     }
492     function loadCompany()
493     {
494         $this->company = $this->company();
495     }
496     
497     function active()
498     { 
499         return $this->active;
500     }
501     function authUserName($n) // set username prior to acheck user exists query.
502     {
503         
504         $this->whereAdd('LENGTH(passwd) > 1'); 
505         $this->email = $n;
506     }
507     function lang()
508     {
509         if (!func_num_args()) {
510             return $this->lang;
511         }
512         $val = array_shift(func_get_args());
513         if ($val == $this->lang) {
514             return;
515         }
516         $uu = clone($this);
517         $this->lang = $val;
518         $this->update($uu);
519         return $this->lang;
520     }
521             
522     
523     function authUserArray()
524     {
525         
526         $aur = $this->toArray();
527         
528         if ($this->id < 1) {
529             return $aur;
530         }
531         
532         
533         //DB_DataObject::debugLevel(1);
534         $c = DB_Dataobject::factory('Companies');
535         $im = DB_Dataobject::factory('Images');
536         $c->joinAdd($im, 'LEFT');
537         $c->selectAdd();
538         $c->selectAs($c, 'company_id_%s');
539         $c->selectAs($im, 'company_id_logo_id_%s');
540         $c->id = $this->company_id;
541         $c->limit(1);
542         $c->find(true);
543         
544         $aur = array_merge( $c->toArray(),$aur);
545         
546         if (empty($c->company_id_logo_id_id))  {
547                  
548             $im = DB_Dataobject::factory('Images');
549             $im->ontable = 'Companies';
550             $im->onid = $c->id;
551             $im->imgtype = 'LOGO';
552             $im->limit(1);
553             $im->selectAdd();
554             $im->selectAs($im,  'company_id_logo_id_%s');
555             if ($im->find(true)) {
556                     
557                 foreach($im->toArray() as $k=>$v) {
558                     $aur[$k] = $v;
559                 }
560             }
561         }
562       
563         // perms + groups.
564         $aur['perms']  = $this->getPerms();
565         $g = DB_DataObject::Factory('group_members');
566         $aur['groups']  = $g->listGroupMembership($this, 'name');
567         
568         $aur['passwd'] = '';
569         $aur['dailykey'] = '';
570         
571         
572         
573         return $aur;
574     }
575     
576     //   ----------PERMS------  ----------------
577     function getPerms() 
578     {
579          //DB_DataObject::debugLevel(1);
580         // find out all the groups they are a member of.. + Default..
581         
582         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
583         
584         $g = DB_DataObject::Factory('group_rights');
585         if (!$g->count()) {
586             $g->genDefault();
587         }
588         
589         if ($this->id < 0) {
590             return $g->adminRights(); // system is not set up - so they get full rights.
591         }
592         //DB_DataObject::debugLevel(1);
593         $g = DB_DataObject::Factory('group_members');
594         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
595         if (!$g->count()) {
596             // add the current user to the admin group..
597             $g = DB_DataObject::Factory('Groups');
598             if ($g->get('name', 'Administrators')) {
599                 $gm = DB_DataObject::Factory('group_members');
600                 $gm->group_id = $g->id;
601                 $gm->user_id = $this->id;
602                 $gm->insert();
603             }
604             
605         }
606         
607         // ------ STANDARD PERMISSION HANDLING.
608         $isOwner = $this->company()->comptype == 'OWNER';
609         $g = DB_DataObject::Factory('group_members');
610         $grps = $g->listGroupMembership($this);
611        //var_dump($grps);
612         $isAdmin = $g->inAdmin;
613         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
614         // the load all the perms for those groups, and add them all together..
615         // then load all those 
616         $g = DB_DataObject::Factory('group_rights');
617         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
618         //echo '<PRE>';print_r($ret);
619         return $ret;
620          
621         
622     }
623     /**
624      *Basic group fetching - probably needs to filter by type eventually.
625      *
626      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
627      */
628     
629     function groups($what=false)
630     {
631         $g = DB_DataObject::Factory('group_members');
632         $grps = $g->listGroupMembership($this);
633         $g = DB_DataObject::Factory('Groups');
634         $g->whereAddIn('id', $grps, 'int');
635         return $g->fetchAll($what);
636         
637     }
638     
639     
640     
641     function hasPerm($name, $lvl) 
642     {
643         static $pcache = array();
644         
645         if (!isset($pcache[$this->id])) {
646             $pcache[$this->id] = $this->getPerms();
647         }
648        // echo "<PRE>";print_r($pcache[$au->id]);
649        // var_dump($pcache[$au->id]);
650         if (empty($pcache[$this->id][$name])) {
651             return false;
652         }
653         
654         return strpos($pcache[$this->id][$name], $lvl) > -1;
655         
656     }    
657     
658     //  ------------ROO HOOKS------------------------------------
659     function applyFilters($q, $au, $roo)
660     {
661         //DB_DataObject::DebugLevel(1);
662         if (!empty($q['query']['person_not_internal'])) {
663             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
664         }
665         
666         
667         if (!empty($q['query']['person_internal_only_all'])) {
668             
669             
670             // must be internal and not current user (need for distribution list)
671             // user has a projectdirectory entry and role is not blank.
672             //DB_DataObject::DebugLevel(1);
673             $pd = DB_DataObject::factory('ProjectDirectory');
674             $pd->whereAdd("role != ''");
675             $pd->selectAdd();
676             $pd->selectAdd('distinct(person_id) as person_id');
677             $roled = $pd->fetchAll('person_id');
678             $rs = $roled  ? "  OR
679                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
680                     " : '';
681             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
682             
683         }
684         // -- for distribution
685         if (!empty($q['query']['person_internal_only'])) {
686             // must be internal and not current user (need for distribution list)
687             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
688             
689             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
690             //    ".id  != ".$au->id);
691             $this->whereAdd("Person.id != {$au->id}");
692         } 
693         
694         if (!empty($q['query']['comptype_or_company_id'])) {
695            // DB_DataObject::debugLevel(1);
696             $bits = explode(',', $q['query']['comptype_or_company_id']);
697             $id = (int) array_pop($bits);
698             $ct = $this->escape($bits[0]);
699             
700             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
701             
702         }
703         
704         
705         // staff list..
706         if (!empty($q['query']['person_inactive'])) {
707            // DB_Dataobject::debugLevel(1);
708             $this->active = 1;
709         }
710         $tn_p = $this->tableName();
711         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
712         $tn_g = DB_DataObject::Factory('Groups')->tableName();
713
714         ///---------------- Group views --------
715         if (!empty($q['query']['in_group'])) {
716             // DB_DataObject::debugLevel(1);
717             $ing = (int) $q['query']['in_group'];
718             if ($q['query']['in_group'] == -1) {
719              
720                 // list all staff who are not in a group.
721                 $this->whereAdd("Person.id NOT IN (
722                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
723                         $tn_g ON $tn_g.id = $tn_gm.group_id
724                         WHERE $tn_g.type = ".$q['query']['type']."
725                     )");
726                 
727                 
728             } else {
729                 
730                 $this->whereAdd("$tn_p.id IN (
731                     SELECT distinct(user_id) FROM $tn_gm
732                         WHERE group_id = $ing
733                     )");
734                }
735             
736         }
737         
738         if (!empty($q['query']['not_in_directory'])) { 
739             // it's a Person list..
740             // DB_DATaobjecT::debugLevel(1);
741             
742             // specific to project directory which is single comp. login
743             //
744             $owncomp = DB_DataObject::Factory('Companies');
745             $owncomp->get('comptype', 'OWNER');
746             if ($q['company_id'] == $owncomp->id) {
747                 $this->active =1;
748             }
749             
750             
751
752             if ( $q['query']['not_in_directory'] > -1) {
753                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
754                 // can list current - so that it does not break!!!
755                 $this->whereAdd("$tn_p.id NOT IN 
756                     ( SELECT distinct person_id FROM $tn_pd WHERE
757                         project_id = " . $q['query']['not_in_directory'] . " AND 
758                         company_id = " . $this->company_id . ')');
759             }
760         }
761            
762         if (!empty($q['query']['role'])) { 
763             // it's a Person list..
764             // DB_DATaobjecT::debugLevel(1);
765             
766             // specific to project directory which is single comp. login
767             //
768             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
769                 // can list current - so that it does not break!!!
770             $this->whereAdd("$tn_p.id IN 
771                     ( SELECT distinct person_id FROM $tn_pd WHERE
772                         role = '". $this->escape($q['query']['role']) ."'
773             )");
774         
775         }
776         
777         
778         if (!empty($q['query']['project_member_of'])) {
779                // this is also a flag to return if they are a member..
780             //DB_DataObject::debugLevel(1);
781             $do = DB_DataObject::factory('ProjectDirectory');
782             $do->project_id = $q['query']['project_member_of'];
783             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
784             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
785             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
786                 
787                 
788             if (!empty($q['query']['project_member_filter'])) {
789                 $this->having('is_member !=0');
790             
791             }
792             
793         }
794         
795         if(!empty($q['query']['name'])){
796             $this->whereAdd("
797                 Person.name LIKE '%{$this->escape($q['query']['name'])}%'
798             ");
799         }
800         
801         if (!empty($q['query']['search'])) {
802             
803             // use our magic search builder...
804             
805              require_once 'Text/SearchParser.php';
806             $x = new Text_SearchParser($q['query']['search']);
807             
808             $props = array(
809                     "$tn_p.name",
810                     "$tn_p.email",
811                     "$tn_p.role",
812                     "$tn_p.phone",
813                     "$tn_p.remarks",
814                     "join_company_id_id.name"
815             );
816             
817             $str =  $x->toSQL(array(
818                 'default' => $props,
819                 'map' => array(
820                     'company' => 'join_company_id_id.name',
821                     //'country' => 'Clipping.country',
822                     //  'media' => 'Clipping.media_name',
823                 ),
824                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
825
826             ));
827             
828             
829             $this->whereAdd($str); /*
830                         $tn_p.name LIKE '%$s%'  OR
831                         $tn_p.email LIKE '%$s%'  OR
832                         $tn_p.role LIKE '%$s%'  OR
833                         $tn_p.phone LIKE '%$s%' OR
834                         $tn_p.remarks LIKE '%$s%' 
835                         
836                     ");*/
837         }
838         
839         //
840     }
841     function setFromRoo($ar, $roo)
842     {
843         $this->setFrom($ar);
844         if (!empty($ar['passwd1'])) {
845             $this->setPassword($ar['passwd1']);
846         }
847         
848         
849         if (    $this->id &&
850                 ($this->email == $roo->old->email)&&
851                 ($this->company_id == $roo->old->company_id)
852             ) {
853             return true;
854         }
855         if (empty($this->email)) {
856             return true;
857         }
858         $xx = DB_Dataobject::factory('Person');
859         $xx->setFrom(array(
860             'email' => $this->email,
861            // 'company_id' => $x->company_id
862         ));
863         
864         if ($xx->count()) {
865             return "Duplicate Email found";
866         }
867         return true;
868     }
869     /**
870      *
871      * before Delete - delete significant dependancies..
872      * this is called after checkPerm..
873      */
874     
875     function beforeDelete()
876     {
877         
878         $e = DB_DataObject::Factory('Events');
879         $e->whereAdd('person_id = ' . $this->id);
880         $e->delete(true);
881         
882         // anything else?  
883         
884     }
885     
886     
887     /***
888      * Check if the a user has access to modify this item.
889      * @param String $lvl Level (eg. Core.Projects)
890      * @param Pman_Core_DataObjects_Person $au The authenticated user.
891      * @param boolean $changes alllow changes???
892      *
893      * @return false if no access..
894      */
895     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
896     {
897          
898        // do we have an empty system..
899         if ($au && $au->id == -1) {
900             return true;
901         }
902         
903         // determine if it's staff!!!
904          
905         if ($au->company()->comptype != 'OWNER') {
906             
907             // - can not change company!!!
908             if ($changes && 
909                 isset($changes['company_id']) && 
910                 $changes['company_id'] != $au->company_id) {
911                 return false;
912             }
913             // can only set new emails..
914             if ($changes && 
915                     !empty($this->email) && 
916                     isset($changes['email']) && 
917                     $changes['email'] != $this->email) {
918                 return false;
919             }
920             
921             // edit self... - what about other staff members...
922             
923             return $this->company_id == $au->company_id;
924         }
925          
926          
927         // yes, only owner company can mess with this...
928         $owncomp = DB_DataObject::Factory('Companies');
929         $owncomp->get('comptype', 'OWNER');
930         
931         $isStaff = ($this->company_id ==  $owncomp->id);
932         
933     
934         switch ($lvl) {
935             // extra case change passwod?
936             case 'P': //??? password
937                 // standard perms -- for editing + if the user is dowing them selves..
938                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
939                 return $ret || $au->id == $this->id;
940             
941             default:                
942                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
943         
944         }
945         return false;
946     }
947     function onInsert($req, $roo)  
948     {
949          
950         $p = DB_DataObject::factory('person');
951         if ($roo->authUser->id < 0 && $p->count() == 1) {
952             // this seems a bit risky...
953             
954             $g = DB_DataObject::factory('Groups');
955             $g->initGroups();
956             
957             $g->type = 0;
958             $g->get('name', 'Administrators');
959             
960             $p = DB_DataObject::factory('group_members');
961             $p->group_id = $g->id;
962             $p->user_id = $this->id;     
963             if (!$p->count()) {
964                 $p->insert();
965                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
966             }
967             $this->login();
968         }
969         if (!empty($req['project_id_addto'])) {
970             $pd = DB_DataObject::factory('ProjectDirectory');
971             $pd->project_id = $req['project_id_addto'];
972             $pd->person_id = $this->id; 
973             $pd->ispm =0;
974             $pd->office_id = $this->office_id;
975             $pd->company_id = $this->company_id;
976             $pd->insert();
977         }
978         
979     }
980     
981     function importFromArray($roo, $persons, $opts)
982     {
983         if (empty($opts['prefix'])) {
984             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
985         }
986         
987         if (!is_array($persons) || empty($persons)) {
988             $roo->jerr("error in the person data. - empty on not valid");
989         }
990         DB_DataObject::factory('groups')->initGroups();
991         
992         foreach($persons as $person){
993             $p = DB_DataObject::factory('person');
994             if($p->get('name', $person['name'])){
995                 continue;
996             }
997             $p->setFrom($person);
998             
999             $companies = DB_DataObject::factory('companies');
1000             if(!$companies->get('comptype', 'OWNER')){
1001                 $roo->jerr("Missing OWNER companies!");
1002             }
1003             $p->company_id = $companies->pid();
1004             // strip the 'spaces etc.. make lowercase..
1005             $name = strtolower(str_replace(' ', '', $person['name']));
1006             $p->setPassword("{$opts['prefix']}{$name}");
1007             $p->insert();
1008             // set up groups
1009             // if $person->groups is set.. then
1010             // add this person to that group eg. groups : [ 'Administrator' ] 
1011             if(!empty($person['groups'])){
1012                 $groups = DB_DataObject::factory('groups');
1013                 if(!$groups->get('name', $person['groups'])){
1014                     $roo->jerr("Missing groups : {$person['groups']}");
1015                 }
1016                 $gm = DB_DataObject::factory('group_members');
1017                 $gm->change($p, $groups, true);
1018             }
1019             
1020             $p->onInsert(array(), $roo);
1021         }
1022     }
1023  }