3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
17 public $company_id; // int(11)
18 public $office_id; // int(11)
19 public $name; // string(128) not_null
20 public $firstname; // string(128) not_null
21 public $lastname; // string(128) not_null
22 public $phone; // string(32) not_null
23 public $fax; // string(32) not_null
25 public $role; // string(32) not_null
26 public $remarks; // blob(65535) not_null blob
27 public $passwd; // string(64) not_null
28 public $owner_id; // int(11) not_null
29 public $lang; // string(8)
30 public $no_reset_sent; // int(11)
31 public $action_type; // string(32)
32 public $project_id; // int(11)
35 public $active; // int(11) not_null
36 public $deleted_by; // int(11) not_null
37 public $deleted_dt; // datetime(19) binary
40 public $name_facebook; // VARCHAR(128) NULL;
41 public $url_blog; // VARCHAR(256) NULL ;
42 public $url_twitter; // VARCHAR(256) NULL ;
43 public $url_linkedin; // VARCHAR(256) NULL ;
45 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
46 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
48 /* the code above is auto generated do not remove the tag below */
53 $p = DB_DataObject::Factory('Person');
54 $p->get($this->owner_id);
63 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
69 function buildMail($templateFile, $args)
72 $args = (array) $args;
73 $content = clone($this);
75 foreach((array)$args as $k=>$v) {
79 $ff = HTML_FlexyFramework::get();
82 //?? is this really the place for this???
85 empty($args['no_auth']) &&
86 !in_array($templateFile, array(
87 // templates that can be sent without authentication.
93 $content->authUser = $this->getAuthUser();
94 if (!$content->authUser) {
95 return PEAR::raiseError("Not authenticated");
99 // should handle x-forwarded...
101 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
102 $_SERVER["HTTP_HOST"] :
103 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
105 /* use the regex compiler, as it doesnt parse <tags */
108 'compiler' => 'Flexy',
110 'filters' => array('SimpleTags','Mail'),
116 if (!empty($args['templateDir'])) {
117 $tops['templateDir'] = $args['templateDir'];
122 require_once 'HTML/Template/Flexy.php';
123 $template = new HTML_Template_Flexy( $tops );
124 $template->compile("mail/$templateFile.txt");
126 /* use variables from this object to ouput data. */
127 $mailtext = $template->bufferedOutputObject($content);
130 // if a html file with the same name exists, use that as the body
131 // I've no idea where this code went, it was here before..
132 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
133 $tops['nonHTML'] = false;
134 $template = new HTML_Template_Flexy( $tops );
135 $template->compile("mail/$templateFile.html");
136 $htmlbody = $template->bufferedOutputObject($content);
142 //echo "<PRE>";print_R($mailtext);
143 //print_R($mailtext);exit;
144 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
145 require_once 'Mail/mimeDecode.php';
146 require_once 'Mail.php';
148 $decoder = new Mail_mimeDecode($mailtext);
149 $parts = $decoder->getSendArray();
151 if (PEAR::isError($parts)) {
153 //echo "PROBLEM: {$parts->message}";
156 list($recipents,$headers,$body) = $parts;
157 $recipents = array($this->email);
158 if (!empty($content->bcc) && is_array($content->bcc)) {
159 $recipents =array_merge($recipents, $content->bcc);
161 $headers['Date'] = date('r');
163 if ($htmlbody !== false) {
164 require_once 'Mail/mime.php';
165 $mime = new Mail_mime(array('eol' => "\n"));
166 $mime->setTXTBody($body);
167 $mime->setHTMLBody($htmlbody);
168 // I think there might be code in mediaoutreach toEmail somewhere
169 // h embeds images here..
170 $body = $mime->get();
171 $headers = $mime->headers($headers);
178 'recipients' => $recipents,
179 'headers' => $headers,
189 * - user must be authenticate or args[no_auth] = true
190 * or template = password_[reset|welcome]
193 function sendTemplate($templateFile, $args)
196 $ar = $this->buildMail($templateFile, $args);
199 //print_r($recipents);exit;
200 $mailOptions = PEAR::getStaticProperty('Mail','options');
201 $mail = Mail::factory("SMTP",$mailOptions);
203 if (PEAR::isError($mail)) {
206 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
207 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
208 error_reporting($oe);
217 function getEmailFrom()
219 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
221 function toEventString()
223 return empty($this->name) ? $this->email : $this->name;
225 function verifyAuth()
227 $ff= HTML_FlexyFramework::get();
228 if (!empty($ff->Pman['auth_comptype']) &&
229 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
232 // force a logout - without a check on the isAuth - as this is called from there..
233 $db = $this->getDatabaseConnection();
234 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
235 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
238 $ff->page->jerr("Login not permited to outside companies");
245 // ---------------- authentication / passwords and keys stuff ----------------
248 $db = $this->getDatabaseConnection();
249 // we combine db + project names,
250 // otherwise if projects use different 'auth' objects
251 // then we get unserialize issues.
252 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
257 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
259 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
261 $u = DB_DataObject::factory('Person');
262 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
264 return $u->verifyAuth();
270 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
274 $u = DB_DataObject::factory('Person');
275 $ff = HTML_FlexyFramework::get();
276 if (!empty($ff->Pman['local_autoauth']) &&
277 (!empty($_SERVER['SERVER_ADDR'])) &&
278 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
279 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
280 $u->get('email', $ff->Pman['local_autoauth'])
282 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
287 $u = DB_DataObject::factory('Person');
289 if (!empty($_SERVER['PHP_AUTH_USER'])
291 !empty($_SERVER['PHP_AUTH_PW'])
293 $u->get('email', $_SERVER['PHP_AUTH_USER'])
295 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
297 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
301 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
305 // not in session or not matched...
306 $u = DB_DataObject::factory('Person');
307 $u->whereAdd(' LENGTH(passwd) > 0');
309 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
310 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
312 die($error->toString()); // not really a good thing to do...
314 if (!$n){ // authenticated as there are no users in the system...
321 function getAuthUser()
323 if (!$this->isAuth()) {
326 $db = $this->getDatabaseConnection();
327 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
331 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
332 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
334 $u = DB_DataObject::factory('Person');
335 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
341 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
342 $u = DB_DataObject::factory('Person');
343 $u->whereAdd(' LENGTH(passwd) > 0');
344 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
348 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
350 // fake person - open system..
351 //$ce = DB_DataObject::factory('core_enum');
355 $u = DB_DataObject::factory('Person');
364 $this->isAuth(); // force session start..
365 if (!$this->verifyAuth()) {
368 $db = $this->getDatabaseConnection();
371 // open up iptables at login..
372 $dbname = $this->database();
373 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
375 // refresh admin group if we are logged in as one..
376 //DB_DataObject::debugLevel(1);
377 $g = DB_DataObject::factory('Groups');
379 $g->get('name', 'Administrators');
380 $gm = DB_DataObject::Factory('group_members');
381 if (in_array($g->id,$gm->listGroupMembership($this))) {
382 // refresh admin groups.
383 $gr = DB_DataObject::Factory('group_rights');
384 $gr->applyDefs($g, 0);
387 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
388 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
393 $this->isAuth(); // force session start..
394 $db = $this->getDatabaseConnection();
395 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
396 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
399 function genPassKey ($t)
401 return md5($this->email . $t. $this->passwd);
403 function simpleAuthKey($m = 0)
405 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
407 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
409 function checkPassword($val)
412 if (substr($this->passwd,0,1) == '$') {
413 return crypt($val,$this->passwd) == $this->passwd ;
415 // old style md5 passwords...- cant be used with courier....
416 return md5($val) == $this->passwd;
418 function setPassword($value)
421 while(strlen($salt)<9) {
422 $salt.=chr(rand(64,126));
423 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
425 $this->passwd = crypt($value, '$1$'. $salt. '$');
430 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
432 require_once 'Text/Password.php';
433 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
434 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
435 $this->setPassword($this->rawPasswd);
436 return $this->rawPasswd;
441 $x = DB_DataObject::factory('Companies');
443 $x->get($this->company_id);
446 function loadCompany()
448 $this->company = $this->company();
453 return $this->active;
455 function authUserName($n) // set username prior to acheck user exists query.
458 $this->whereAdd('LENGTH(passwd) > 1');
463 if ($val == $this->lang) {
473 function authUserArray()
476 $aur = $this->toArray();
483 //DB_DataObject::debugLevel(1);
484 $c = DB_Dataobject::factory('Companies');
485 $im = DB_Dataobject::factory('Images');
486 $c->joinAdd($im, 'LEFT');
488 $c->selectAs($c, 'company_id_%s');
489 $c->selectAs($im, 'company_id_logo_id_%s');
490 $c->id = $this->company_id;
494 $aur = array_merge( $c->toArray(),$aur);
496 if (empty($c->company_id_logo_id_id)) {
498 $im = DB_Dataobject::factory('Images');
499 $im->ontable = 'Companies';
501 $im->imgtype = 'LOGO';
504 $im->selectAs($im, 'company_id_logo_id_%s');
505 if ($im->find(true)) {
507 foreach($im->toArray() as $k=>$v) {
514 $aur['perms'] = $this->getPerms();
515 $g = DB_DataObject::Factory('group_members');
516 $aur['groups'] = $g->listGroupMembership($this, 'name');
519 $aur['dailykey'] = '';
526 // ----------PERMS------ ----------------
529 //DB_DataObject::debugLevel(1);
530 // find out all the groups they are a member of.. + Default..
532 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
534 $g = DB_DataObject::Factory('group_rights');
540 return $g->adminRights(); // system is not set up - so they get full rights.
542 //DB_DataObject::debugLevel(1);
543 $g = DB_DataObject::Factory('group_members');
544 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
546 // add the current user to the admin group..
547 $g = DB_DataObject::Factory('Groups');
548 if ($g->get('name', 'Administrators')) {
549 $gm = DB_DataObject::Factory('group_members');
550 $gm->group_id = $g->id;
551 $gm->user_id = $this->id;
557 // ------ STANDARD PERMISSION HANDLING.
558 $isOwner = $this->company()->comptype == 'OWNER';
559 $g = DB_DataObject::Factory('group_members');
560 $grps = $g->listGroupMembership($this);
562 $isAdmin = $g->inAdmin;
563 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
564 // the load all the perms for those groups, and add them all together..
565 // then load all those
566 $g = DB_DataObject::Factory('group_rights');
567 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
568 //echo '<PRE>';print_r($ret);
574 *Basic group fetching - probably needs to filter by type eventually.
576 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
579 function groups($what=false)
581 $g = DB_DataObject::Factory('group_members');
582 $grps = $g->listGroupMembership($this);
583 $g = DB_DataObject::Factory('Groups');
584 $g->whereAddIn('id', $grps, 'int');
585 return $g->fetchAll($what);
591 function hasPerm($name, $lvl)
593 static $pcache = array();
595 if (!isset($pcache[$this->id])) {
596 $pcache[$this->id] = $this->getPerms();
598 // echo "<PRE>";print_r($pcache[$au->id]);
599 // var_dump($pcache[$au->id]);
600 if (empty($pcache[$this->id][$name])) {
604 return strpos($pcache[$this->id][$name], $lvl) > -1;
608 // ------------ROO HOOKS------------------------------------
609 function applyFilters($q, $au, $roo)
611 //DB_DataObject::DebugLevel(1);
612 if (!empty($q['query']['person_not_internal'])) {
613 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
617 if (!empty($q['query']['person_internal_only_all'])) {
620 // must be internal and not current user (need for distribution list)
621 // user has a projectdirectory entry and role is not blank.
622 //DB_DataObject::DebugLevel(1);
623 $pd = DB_DataObject::factory('ProjectDirectory');
624 $pd->whereAdd("role != ''");
626 $pd->selectAdd('distinct(person_id) as person_id');
627 $roled = $pd->fetchAll('person_id');
629 {$this->tableName()}.id IN (".implode(',', $roled) . ")
631 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
634 // -- for distribution
635 if (!empty($q['query']['person_internal_only'])) {
636 // must be internal and not current user (need for distribution list)
637 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
639 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
640 // ".id != ".$au->id);
641 $this->whereAdd("Person.id != {$au->id}");
644 if (!empty($q['query']['comptype_or_company_id'])) {
645 // DB_DataObject::debugLevel(1);
646 $bits = explode(',', $q['query']['comptype_or_company_id']);
647 $id = (int) array_pop($bits);
648 $ct = $this->escape($bits[0]);
650 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
656 if (!empty($q['query']['person_inactive'])) {
657 // DB_Dataobject::debugLevel(1);
660 $tn_p = $this->tableName();
661 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
662 $tn_g = DB_DataObject::Factory('Groups')->tableName();
664 ///---------------- Group views --------
665 if (!empty($q['query']['in_group'])) {
666 // DB_DataObject::debugLevel(1);
667 $ing = (int) $q['query']['in_group'];
668 if ($q['query']['in_group'] == -1) {
670 // list all staff who are not in a group.
671 $this->whereAdd("Person.id NOT IN (
672 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
673 $tn_g ON $tn_g.id = $tn_gm.group_id
674 WHERE $tn_g.type = ".$q['query']['type']."
680 $this->whereAdd("$tn_p.id IN (
681 SELECT distinct(user_id) FROM $tn_gm
682 WHERE group_id = $ing
688 if (!empty($q['query']['not_in_directory'])) {
689 // it's a Person list..
690 // DB_DATaobjecT::debugLevel(1);
692 // specific to project directory which is single comp. login
694 $owncomp = DB_DataObject::Factory('Companies');
695 $owncomp->get('comptype', 'OWNER');
696 if ($q['company_id'] == $owncomp->id) {
702 if ( $q['query']['not_in_directory'] > -1) {
703 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
704 // can list current - so that it does not break!!!
705 $this->whereAdd("$tn_p.id NOT IN
706 ( SELECT distinct person_id FROM $tn_pd WHERE
707 project_id = " . $q['query']['not_in_directory'] . " AND
708 company_id = " . $this->company_id . ')');
712 if (!empty($q['query']['role'])) {
713 // it's a Person list..
714 // DB_DATaobjecT::debugLevel(1);
716 // specific to project directory which is single comp. login
718 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
719 // can list current - so that it does not break!!!
720 $this->whereAdd("$tn_p.id IN
721 ( SELECT distinct person_id FROM $tn_pd WHERE
722 role = '". $this->escape($q['query']['role']) ."'
728 if (!empty($q['query']['project_member_of'])) {
729 // this is also a flag to return if they are a member..
730 //DB_DataObject::debugLevel(1);
731 $do = DB_DataObject::factory('ProjectDirectory');
732 $do->project_id = $q['query']['project_member_of'];
733 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
734 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
735 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
738 if (!empty($q['query']['project_member_filter'])) {
739 $this->having('is_member !=0');
745 if (!empty($q['query']['search'])) {
747 // use our magic search builder...
749 require_once 'Text/SearchParser.php';
750 $x = new Text_SearchParser($q['query']['search']);
758 "join_company_id_id.name"
761 $str = $x->toSQL(array(
764 'company' => 'join_company_id_id.name',
765 //'country' => 'Clipping.country',
766 // 'media' => 'Clipping.media_name',
768 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
773 $this->whereAdd($str); /*
774 $tn_p.name LIKE '%$s%' OR
775 $tn_p.email LIKE '%$s%' OR
776 $tn_p.role LIKE '%$s%' OR
777 $tn_p.phone LIKE '%$s%' OR
778 $tn_p.remarks LIKE '%$s%'
785 function setFromRoo($ar, $roo)
788 if (!empty($ar['passwd1'])) {
789 $this->setPassword($ar['passwd1']);
794 ($this->email == $roo->old->email)&&
795 ($this->company_id == $roo->old->company_id)
799 if (empty($this->email)) {
802 $xx = DB_Dataobject::factory('Person');
804 'email' => $this->email,
805 // 'company_id' => $x->company_id
809 return "Duplicate Email found";
815 * before Delete - delete significant dependancies..
816 * this is called after checkPerm..
819 function beforeDelete()
822 $e = DB_DataObject::Factory('Events');
823 $e->whereAdd('person_id = ' . $this->id);
832 * Check if the a user has access to modify this item.
833 * @param String $lvl Level (eg. Core.Projects)
834 * @param Pman_Core_DataObjects_Person $au The authenticated user.
835 * @param boolean $changes alllow changes???
837 * @return false if no access..
839 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
842 // do we have an empty system..
843 if ($au && $au->id == -1) {
847 // determine if it's staff!!!
849 if ($au->company()->comptype != 'OWNER') {
851 // - can not change company!!!
853 isset($changes['company_id']) &&
854 $changes['company_id'] != $au->company_id) {
857 // can only set new emails..
859 !empty($this->email) &&
860 isset($changes['email']) &&
861 $changes['email'] != $this->email) {
865 // edit self... - what about other staff members...
867 return $this->company_id == $au->company_id;
871 // yes, only owner company can mess with this...
872 $owncomp = DB_DataObject::Factory('Companies');
873 $owncomp->get('comptype', 'OWNER');
875 $isStaff = ($this->company_id == $owncomp->id);
879 // extra case change passwod?
880 case 'P': //??? password
881 // standard perms -- for editing + if the user is dowing them selves..
882 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
883 return $ret || $au->id == $this->id;
886 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
891 function onInsert($req, $roo)
894 $p = DB_DataObject::factory('person');
895 if ($roo->authUser->id < 0 && $p->count() == 1) {
896 // this seems a bit risky...
898 $g = DB_DataObject::factory('Groups');
902 $g->get('name', 'Administrators');
904 $p = DB_DataObject::factory('group_members');
905 $p->group_id = $g->id;
906 $p->user_id = $this->id;
909 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
913 if (!empty($req['project_id_addto'])) {
914 $pd = DB_DataObject::factory('ProjectDirectory');
915 $pd->project_id = $req['project_id_addto'];
916 $pd->person_id = $this->id;
918 $pd->office_id = $this->office_id;
919 $pd->company_id = $this->company_id;
925 function importFromArray($roo, $persons, $prefix)
927 if (!is_array($persons) || empty($persons)) {
928 $roo->jerr("error in the person data. - empty on not valid");
930 DB_DataObject::factory('groups')->initGroups();
932 foreach($persons as $person){
933 $p = DB_DataObject::factory('person');
934 if($p->get('name', $person['name'])){
937 $p->setFrom($person);
939 $companies = DB_DataObject::factory('companies');
940 if(!$companies->get('comptype', 'OWNER')){
941 $roo->jerr("Missing OWNER companies!");
943 $p->company_id = $companies->pid();
944 // strip the 'spaces etc.. make lowercase..
945 $name = strtolower(str_replace(' ', '', $person['name']));
946 $p->setPassword("$prefix$name");
949 // if $person->groups is set.. then
950 // add this person to that group eg. groups : [ 'Administrator' ]
951 if(!empty($person['groups'])){
952 $groups = DB_DataObject::factory('groups');
953 if(!$groups->get('name', $person['groups'])){
954 $roo->jerr("Missing groups : {$person['groups']}");
956 $gm = DB_DataObject::factory('group_members');
957 $gm->change($p, $groups, true);
960 $p->onInsert(array(), $roo);