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