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