3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
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
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)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
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 public $linkedin_id; // VARCHAR(256) NULL ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
54 static $authUser = false;
59 // this might be a Person in some old code?
60 $p = DB_DataObject::Factory('core_person');
61 $p->get($this->owner_id);
70 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
76 function buildMail($templateFile, $args)
79 $args = (array) $args;
80 $content = clone($this);
82 foreach((array)$args as $k=>$v) {
86 $ff = HTML_FlexyFramework::get();
89 //?? is this really the place for this???
92 empty($args['no_auth']) &&
93 !in_array($templateFile, array(
94 // templates that can be sent without authentication.
100 $content->authUser = $this->getAuthUser();
101 if (!$content->authUser) {
102 return PEAR::raiseError("Not authenticated");
106 // should handle x-forwarded...
108 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
109 $_SERVER["HTTP_HOST"] :
110 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
112 /* use the regex compiler, as it doesnt parse <tags */
115 'compiler' => 'Flexy',
117 'filters' => array('SimpleTags','Mail'),
123 if (!empty($args['templateDir'])) {
124 $tops['templateDir'] = $args['templateDir'];
129 require_once 'HTML/Template/Flexy.php';
130 $template = new HTML_Template_Flexy( $tops );
131 $template->compile("mail/$templateFile.txt");
133 /* use variables from this object to ouput data. */
134 $mailtext = $template->bufferedOutputObject($content);
137 // if a html file with the same name exists, use that as the body
138 // I've no idea where this code went, it was here before..
139 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
140 $tops['nonHTML'] = false;
141 $template = new HTML_Template_Flexy( $tops );
142 $template->compile("mail/$templateFile.html");
143 $htmlbody = $template->bufferedOutputObject($content);
149 //echo "<PRE>";print_R($mailtext);
150 //print_R($mailtext);exit;
151 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
152 require_once 'Mail/mimeDecode.php';
153 require_once 'Mail.php';
155 $decoder = new Mail_mimeDecode($mailtext);
156 $parts = $decoder->getSendArray();
158 if (is_a($parts,'PEAR_Error')) {
160 //echo "PROBLEM: {$parts->message}";
163 list($recipents,$headers,$body) = $parts;
164 $recipents = array($this->email);
165 if (!empty($content->bcc) && is_array($content->bcc)) {
166 $recipents =array_merge($recipents, $content->bcc);
168 $headers['Date'] = date('r');
170 if ($htmlbody !== false) {
171 require_once 'Mail/mime.php';
172 $mime = new Mail_mime(array('eol' => "\n"));
173 $mime->setTXTBody($body);
174 $mime->setHTMLBody($htmlbody);
175 // I think there might be code in mediaoutreach toEmail somewhere
176 // h embeds images here..
177 $body = $mime->get();
178 $headers = $mime->headers($headers);
182 'recipients' => $recipents,
183 'headers' => $headers,
191 * - user must be authenticate or args[no_auth] = true
192 * or template = password_[reset|welcome]
195 function sendTemplate($templateFile, $args)
197 $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);
216 function getEmailFrom()
218 if (empty($this->name)) {
222 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
225 function toEventString()
227 return empty($this->name) ? $this->email : $this->name;
230 function verifyAuth()
232 $ff= HTML_FlexyFramework::get();
233 if (!empty($ff->Pman['auth_comptype']) &&
234 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
237 $sesPrefix = $this->sesPrefix();
239 self::$authUser = false;
240 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
244 //$ff->page->jerr("Login not permited to outside companies");
251 // ---------------- authentication / passwords and keys stuff ----------------
254 // do not start a session if we are using http auth...
255 if (empty($_SERVER['PHP_AUTH_USER']) && php_sapi_name() != "cli") {
259 $ff= HTML_FlexyFramework::get();
261 $sesPrefix = $this->sesPrefix();
263 if (self::$authUser) {
264 return self::$authUser;
268 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
270 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
271 $u = DB_DataObject::factory($this->tableName());
273 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
274 if ($u->verifyAuth()) {
275 self::$authUser = $u;
279 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
280 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
281 setcookie('Pman.timeout', -1, time() + (30*60), '/');
286 $u = DB_DataObject::factory($this->tableName());
288 if (!empty($_SERVER['PHP_AUTH_USER'])
290 !empty($_SERVER['PHP_AUTH_PW'])
292 $u->get('email', $_SERVER['PHP_AUTH_USER'])
294 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
296 // logged in via http auth
297 // http auth will not need session...
298 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
299 self::$authUser = $u;
303 if (!$this->canInitializeSystem()) {
304 // die("can not init");
309 $auto_auth_allow = false;
310 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
311 $auto_auth_allow = true;
313 if ( !empty($ff->Pman['local_autoauth'])
315 !empty($_SERVER['SERVER_ADDR']) &&
316 !empty($_SERVER['REMOTE_ADDR']) &&
319 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
320 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
324 $_SERVER['SERVER_ADDR'] == '::1' &&
325 $_SERVER['REMOTE_ADDR'] == '::1'
330 $auto_auth_allow = true;
334 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
335 $auto_auth_allow = false;
337 //var_dump($auto_auth_allow);
339 $default_admin = false;
340 if ($auto_auth_allow) {
341 $group = DB_DataObject::factory('core_group');
342 $group->get('name', 'Administrators');
344 $member = DB_DataObject::factory('core_group_member');
346 $member->group_id = $group->id;
348 join_user_id_id.id IS NOT NULL
350 if($member->find(true)){
351 $default_admin = DB_DataObject::factory($this->tableName());
352 $default_admin->autoJoin();
353 if(!$default_admin->get($member->user_id)){
354 $default_admin = false;
359 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
360 $u = DB_DataObject::factory($this->tableName());
362 $ff = HTML_FlexyFramework::get();
364 if ($auto_auth_allow &&
365 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
368 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
370 // if we request other URLS.. then we get auto logged in..
371 self::$authUser = $default_admin ? $default_admin : $u;;
372 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
376 //var_dump(session_id());
377 //var_dump($_SESSION[__CLASS__]);
379 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
382 //die("got this far?");
383 // not in session or not matched...
384 $u = DB_DataObject::factory($this->tableName());
385 $u->whereAdd(' LENGTH(passwd) > 0');
387 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
388 if (class_exists('PEAR')) {
389 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
391 die($error->toString()); // not really a good thing to do...
394 if (!$n){ // authenticated as there are no users in the system...
401 function canInitializeSystem()
404 return !strcasecmp(get_class($this) , __CLASS__);
407 function getAuthUser()
409 if (!$this->isAuth()) {
413 $ff= HTML_FlexyFramework::get();
415 $sesPrefix = $this->sesPrefix();
417 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
419 if (self::$authUser) {
421 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
422 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
423 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
425 // not really sure why it's cloned..
426 return clone (self::$authUser);
433 if (!$this->canInitializeSystem()) {
439 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
440 $u = DB_DataObject::factory($this->tableName());
441 $u->whereAdd(' LENGTH(passwd) > 0');
442 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
447 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
448 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
451 // fake person - open system..
452 //$ce = DB_DataObject::factory('core_enum');
456 $u = DB_DataObject::factory($this->tableName());
459 // if a company has been created fill that in in company_id_id
460 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
462 $u->company_id_id = $c->pid();
463 $u->company_id = $c->pid();
473 $this->isAuth(); // force session start..
474 if (!$this->verifyAuth()) { // check for company valid..
478 // open up iptables at login..
479 $dbname = $this->databaseNickname();
480 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
482 // refresh admin group if we are logged in as one..
483 //DB_DataObject::debugLevel(1);
484 $g = DB_DataObject::factory('core_group');
486 $g->get('name', 'Administrators');
487 $gm = DB_DataObject::Factory('core_group_member');
488 if (in_array($g->id,$gm->listGroupMembership($this))) {
489 // refresh admin groups.
490 $gr = DB_DataObject::Factory('core_group_right');
491 $gr->applyDefs($g, 0);
494 $sesPrefix = $this->sesPrefix();
496 // we should not store the whole data in the session - otherwise it get's huge.
497 $p = DB_DAtaObject::Factory($this->tableName());
498 $p->get($this->pid());
502 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
503 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
505 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
506 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
508 $pp = DB_DAtaObject::Factory($this->tableName());
509 $pp->get($this->pid());
512 self::$authUser = $pp;
513 // ensure it's written so that ajax calls can fetch it..
520 $this->isAuth(); // force session start..
522 $sesPrefix = $this->sesPrefix();
524 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
526 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
528 self::$authUser = false;
531 function genPassKey ($t)
533 return md5($this->email . $t. $this->passwd);
535 function simpleAuthKey($m = 0)
537 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
539 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
542 * When we generate autologin urls:
543 * eg. /Somesite/Test/12
545 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
547 * eg. genAutoLoginURL($sub, $expires)
549 function genAutoLoginURL($url, $expires = false)
551 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
552 echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
554 return $url.'/'.$this->id .'/'.$expires.'/'.
557 array($url, $expires, $this->email,$this->passwd)
563 function validateAutoLogin($called)
565 $bits = explode("/",$called);
566 $hash = array_pop($bits);
567 $time = array_pop($bits);
568 $id = array_pop($bits);
569 $u = DB_DataObject::Factory($this->tableName());
571 $url = implode("/", $bits);
572 if ($time < time()) {
575 echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
576 echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
577 if ($hash == hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)))) {
585 function checkTwoFactorAuthentication($val)
589 // also used in login
590 require_once 'System.php';
594 empty($this->oath_key)
599 $oathtool = System::which('oathtool');
605 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
607 $password = exec($cmd);
609 return ($password == $val) ? true : false;
612 function checkPassword($val)
614 if (substr($this->passwd,0,1) == '$') {
615 if (function_exists('pasword_verify')) {
616 return password_verify($val, $this->passwd);
618 return crypt($val,$this->passwd) == $this->passwd ;
620 // old style md5 passwords...- cant be used with courier....
621 return md5($val) == $this->passwd;
624 function setPassword($value)
626 if (function_exists('pasword_hash')) {
627 return password_hash($value);
631 while(strlen($salt)<9) {
632 $salt.=chr(rand(64,126));
633 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
635 $this->passwd = crypt($value, '$1$'. $salt. '$');
640 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
642 require_once 'Text/Password.php';
643 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
644 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
645 $this->setPassword($this->rawPasswd);
646 return $this->rawPasswd;
651 if (empty($this->company_id)) {
654 $x = DB_DataObject::factory('core_company');
656 $x->get($this->company_id);
659 function loadCompany()
661 $this->company = $this->company();
666 return $this->active;
668 function authUserName($n) // set username prior to acheck user exists query.
671 $this->whereAdd('LENGTH(passwd) > 1');
676 if (!func_num_args()) {
679 $ar = func_get_args();
680 $val = array_shift($ar);
681 if ($val == $this->lang) {
691 function authUserArray()
693 $aur = $this->toArray();
699 //DB_DataObject::debugLevel(1);
700 $c = DB_Dataobject::factory('core_company');
701 $im = DB_Dataobject::factory('Images');
702 $c->joinAdd($im, 'LEFT');
704 $c->selectAs($c, 'company_id_%s');
705 $c->selectAs($im, 'company_id_logo_id_%s');
706 $c->id = $this->company_id;
710 $aur = array_merge( $c->toArray(),$aur);
712 if (empty($c->company_id_logo_id_id)) {
714 $im = DB_Dataobject::factory('Images');
715 $im->ontable = DB_DataObject::factory('core_company')->tableName();
717 $im->imgtype = 'LOGO';
720 $im->selectAs($im, 'company_id_logo_id_%s');
721 if ($im->find(true)) {
723 foreach($im->toArray() as $k=>$v) {
724 if (!preg_match('/^company_id_logo_id_/', $k)) {
733 $aur['perms'] = $this->getPerms();
734 $g = DB_DataObject::Factory('core_group_member');
735 $aur['groups'] = $g->listGroupMembership($this, 'name');
738 $aur['dailykey'] = '';
739 $aur['oath_key'] = '';
741 $aur['oath_key_enable'] = !empty($this->oath_key);
742 $aur['require_oath'] = 1;
744 $s = DB_DataObject::Factory('core_setting');
745 $oath_require = $s->lookup('core', 'two_factor_auth_required');
746 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
748 $aur['core_person_settings'] = array();
750 $core_person_settings = DB_DataObject::factory('core_person_settings');
751 $core_person_settings->setFrom(array(
752 'person_id' => $this->id
755 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
760 // ----------PERMS------ ----------------
763 //DB_DataObject::debugLevel(1);
764 // find out all the groups they are a member of.. + Default..
766 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
768 $g = DB_DataObject::Factory('core_group_right');
774 return $g->adminRights(); // system is not set up - so they get full rights.
776 //DB_DataObject::debugLevel(1);
777 $g = DB_DataObject::Factory('core_group_member');
778 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
780 // add the current user to the admin group..
781 $g = DB_DataObject::Factory('core_group');
782 if ($g->get('name', 'Administrators')) {
783 $gm = DB_DataObject::Factory('core_group_member');
784 $gm->group_id = $g->id;
785 $gm->user_id = $this->id;
791 // ------ STANDARD PERMISSION HANDLING.
792 $isOwner = $this->company()->comptype == 'OWNER';
793 $g = DB_DataObject::Factory('core_group_member');
794 $grps = $g->listGroupMembership($this);
796 $isAdmin = $g->inAdmin; //??? what???
797 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
798 // the load all the perms for those groups, and add them all together..
799 // then load all those
800 $g = DB_DataObject::Factory('core_group_right');
801 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
802 //echo '<PRE>';print_r($ret);
808 *Basic group fetching - probably needs to filter by type eventually.
810 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
813 function groups($what=false)
815 $g = DB_DataObject::Factory('core_group_member');
816 $grps = $g->listGroupMembership($this);
817 $g = DB_DataObject::Factory('core_group');
818 $g->whereAddIn('id', $grps, 'int');
819 return $g->fetchAll($what);
825 function hasPerm($name, $lvl)
827 static $pcache = array();
829 if (!isset($pcache[$this->id])) {
830 $pcache[$this->id] = $this->getPerms();
833 // echo "<PRE>";print_r($pcache[$au->id]);
834 // var_dump($pcache[$au->id]);
835 if (empty($pcache[$this->id][$name])) {
839 return strpos($pcache[$this->id][$name], $lvl) > -1;
843 // ------------ROO HOOKS------------------------------------
844 function applyFilters($q, $au, $roo)
846 //DB_DataObject::DebugLevel(1);
847 if(!empty($q['_to_qr_code'])){
848 $person = DB_DataObject::factory('Core_person');
849 $person->id = $q['id'];
851 if(!$person->find(true)) {
852 $roo->jerr('_invalid_person');
855 $hash = $this->generateOathKey();
857 $_SESSION[__CLASS__] =
858 isset($_SESSION[__CLASS__]) ?
859 $_SESSION[__CLASS__] : array();
860 $_SESSION[__CLASS__]['oath'] =
861 isset($_SESSION[__CLASS__]['oath']) ?
862 $_SESSION[__CLASS__]['oath'] : array();
864 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
866 $qrcode = $person->generateQRCode($hash);
869 $roo->jerr('Fail to generate QR Code');
875 'issuer' => $person->qrCodeIssuer()
879 if(!empty($q['two_factor_auth_code'])) {
880 $person = DB_DataObject::factory('core_person');
881 $person->get($q['id']);
883 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
885 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
887 unset($_SESSION[__CLASS__]['oath'][$person->id]);
891 $roo->jerr('_invalid_auth_code');
894 if(!empty($q['oath_key_disable'])) {
895 $person = DB_DataObject::factory('core_person');
896 $person->get($q['id']);
900 $person->oath_key = '';
906 if (!empty($q['query']['is_owner'])) {
907 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
910 if (!empty($q['query']['person_not_internal'])) {
911 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
914 if (!empty($q['query']['person_internal_only_all'])) {
917 // must be internal and not current user (need for distribution list)
918 // user has a projectdirectory entry and role is not blank.
919 //DB_DataObject::DebugLevel(1);
920 $pd = DB_DataObject::factory('ProjectDirectory');
921 $pd->whereAdd("role != ''");
923 $pd->selectAdd('distinct(person_id) as person_id');
924 $roled = $pd->fetchAll('person_id');
926 {$this->tableName()}.id IN (".implode(',', $roled) . ")
928 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
931 // -- for distribution
932 if (!empty($q['query']['person_internal_only'])) {
933 // must be internal and not current user (need for distribution list)
934 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
936 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
937 // ".id != ".$au->id);
938 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
941 if (!empty($q['query']['comptype_or_company_id'])) {
942 // DB_DataObject::debugLevel(1);
943 $bits = explode(',', $q['query']['comptype_or_company_id']);
944 $id = (int) array_pop($bits);
945 $ct = $this->escape($bits[0]);
947 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
953 if (!empty($q['query']['person_inactive'])) {
954 // DB_Dataobject::debugLevel(1);
957 $tn_p = $this->tableName();
958 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
959 $tn_g = DB_DataObject::Factory('core_group')->tableName();
961 ///---------------- Group views --------
962 if (!empty($q['query']['in_group'])) {
963 // DB_DataObject::debugLevel(1);
964 $ing = (int) $q['query']['in_group'];
965 if ($q['query']['in_group'] == -1) {
967 // list all staff who are not in a group.
968 $this->whereAdd("{$this->tableName()}.id NOT IN (
969 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
970 $tn_g ON $tn_g.id = $tn_gm.group_id)");
974 $this->whereAdd("$tn_p.id IN (
975 SELECT distinct(user_id) FROM $tn_gm
976 WHERE group_id = $ing
982 if(!empty($q['in_group_name'])){
984 $v = $this->escape($q['in_group_name']);
989 DISTINCT(user_id) FROM $tn_gm
993 $tn_g.id = $tn_gm.group_id
1000 // #2307 Search Country!!
1001 if (!empty($q['query']['in_country'])) {
1002 // DB_DataObject::debugLevel(1);
1003 $inc = $q['query']['in_country'];
1004 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1007 if (!empty($q['query']['not_in_directory'])) {
1008 // it's a Person list..
1009 // DB_DATaobjecT::debugLevel(1);
1011 // specific to project directory which is single comp. login
1013 $owncomp = DB_DataObject::Factory('core_company');
1014 $owncomp->get('comptype', 'OWNER');
1015 if ($q['company_id'] == $owncomp->id) {
1021 if ( $q['query']['not_in_directory'] > -1) {
1022 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1023 // can list current - so that it does not break!!!
1024 $this->whereAdd("$tn_p.id NOT IN
1025 ( SELECT distinct person_id FROM $tn_pd WHERE
1026 project_id = " . $q['query']['not_in_directory'] . " AND
1027 company_id = " . $this->company_id . ')');
1031 if (!empty($q['query']['role'])) {
1032 // it's a Person list..
1033 // DB_DATaobjecT::debugLevel(1);
1035 // specific to project directory which is single comp. login
1037 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1038 // can list current - so that it does not break!!!
1039 $this->whereAdd("$tn_p.id IN
1040 ( SELECT distinct person_id FROM $tn_pd WHERE
1041 role = '". $this->escape($q['query']['role']) ."'
1047 if (!empty($q['query']['project_member_of'])) {
1048 // this is also a flag to return if they are a member..
1049 //DB_DataObject::debugLevel(1);
1050 $do = DB_DataObject::factory('ProjectDirectory');
1051 $do->project_id = $q['query']['project_member_of'];
1052 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1053 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1054 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1057 if (!empty($q['query']['project_member_filter'])) {
1058 $this->having('is_member !=0');
1064 if(!empty($q['query']['name'])){
1066 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1069 if(!empty($q['query']['name_starts'])){
1071 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1075 if (!empty($q['query']['search'])) {
1077 // use our magic search builder...
1079 require_once 'Text/SearchParser.php';
1080 $x = new Text_SearchParser($q['query']['search']);
1088 "join_company_id_id.name"
1090 $tbcols = $this->table();
1091 foreach(array('firstname','lastname') as $k) {
1092 if (isset($tbcols[$k])) {
1093 $props[] = "{$tn_p}.{$k}";
1100 $str = $x->toSQL(array(
1101 'default' => $props,
1103 'company' => 'join_company_id_id.name',
1104 //'country' => 'Clipping.country',
1105 // 'media' => 'Clipping.media_name',
1107 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1112 $this->whereAdd($str); /*
1113 $tn_p.name LIKE '%$s%' OR
1114 $tn_p.email LIKE '%$s%' OR
1115 $tn_p.role LIKE '%$s%' OR
1116 $tn_p.phone LIKE '%$s%' OR
1117 $tn_p.remarks LIKE '%$s%'
1122 // project directory rules -- this may distrupt things.
1123 $p = DB_DataObject::factory('ProjectDirectory');
1124 // if project directories are set up, then we can apply project query rules..
1127 $pids = $p->projects($au);
1128 if (isset($q['query']['project_id'])) {
1129 $pid = (int)$q['query']['project_id'];
1130 if (!in_array($pid, $pids)) {
1131 $roo->jerr("Project not in users valid projects");
1133 $pids = array($pid);
1136 //if (empty($q['_anyrole'])) { // should be project_directry_role
1137 // $p->whereAdd("{$p->tableName()}.role != ''");
1139 if (!empty($q['query']['role'])) { // should be project_directry_role
1140 $role = $this->escape($q['query']['role']);
1142 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1146 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1147 $peps = $p->people($pids);
1148 $this->whereAddIn("{$tn}.id", $peps, 'int');
1152 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1153 if (isset($q['query']['ticket_id'])) {
1154 // find out what state the ticket is in.
1155 $t = DB_DataObject::Factory('mtrack_ticket');
1157 $t->get($q['query']['ticket_id']);
1159 if (!$this->checkPerm('S', $au)) {
1160 $roo->jerr("permssion denied to query state of ticket");
1163 $p = DB_DataObject::factory('ProjectDirectory');
1164 $pids = array($t->project_id);
1166 $peps = $p->people($pids);
1168 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1170 //$this->whereAdd('join_prole != ''");
1175 * Seems we never expose oath_key / passwd, so...
1178 if($this->tableName() == 'core_person'){
1179 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1182 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1183 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1186 if (isset($q['_with_group_membership'])) {
1187 $this->selectAddGroupMemberships();
1192 function selectAddGroupMemberships()
1198 GROUP_CONCAT( core_group.name separator '\n')
1204 core_group.id = core_group_member.group_id
1206 core_group_member.user_id = core_person.id
1207 ), '') as member_of");
1210 function setFromRoo($ar, $roo)
1212 $this->setFrom($ar);
1214 if(!empty($ar['_enable_oath_key'])){
1215 $oath_key = $this->generateOathKey();
1218 if (!empty($ar['passwd1'])) {
1219 $this->setPassword($ar['passwd1']);
1223 ($this->email == $roo->old->email)&&
1224 ($this->company_id == $roo->old->company_id)
1228 if (empty($this->email)) {
1231 // this only applies to our owner company..
1232 $c = $this->company();
1233 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1238 $xx = DB_Dataobject::factory($this->tableName());
1240 'email' => $this->email,
1241 // 'company_id' => $x->company_id
1245 return "Duplicate Email found";
1252 * before Delete - delete significant dependancies..
1253 * this is called after checkPerm..
1256 function beforeDelete($dependants_array, $roo)
1258 //delete group membership except for admin group..
1259 // if they are a member of admin group do not delete anything.
1260 $default_admin = false;
1262 $e = DB_DataObject::Factory('Events');
1263 $e->whereAdd('person_id = ' . $this->id);
1265 $g = DB_DataObject::Factory('core_group');
1266 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1268 $p = DB_DataObject::Factory('core_group_member');
1270 'user_id' => $this->id,
1271 'group_id' => $g->id
1275 $roo->jerr("Please remove this user from the Administrator group before deleting");
1279 $p = DB_DataObject::Factory('core_group_member');
1280 $p->user_id = $this->id;
1281 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1282 $e->logDeletedRecord($mem);
1284 foreach($mem as $p) {
1288 $e = DB_DataObject::Factory('Events');
1289 $e->person_id = $this->id;
1290 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1292 $e->logDeletedRecord($eve);
1293 foreach($eve as $e) {
1304 * Check if the a user has access to modify this item.
1305 * @param String $lvl Level (eg. Core.Projects)
1306 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1307 * @param boolean $changes alllow changes???
1309 * @return false if no access..
1311 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1314 // do we have an empty system..
1315 if ($au && $au->id == -1) {
1318 // if not authenticated... do not allow in???
1323 // determine if it's staff!!!
1324 $owncomp = DB_DataObject::Factory('core_company');
1325 $owncomp->get('comptype', 'OWNER');
1326 $isStaff = ($au->company_id == $owncomp->id);
1331 // - can not change company!!!
1333 isset($changes['company_id']) &&
1334 $changes['company_id'] != $au->company_id) {
1337 // can only set new emails..
1339 !empty($this->email) &&
1340 isset($changes['email']) &&
1341 $changes['email'] != $this->email) {
1346 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1347 // ???? do we want this?
1349 // edit self... - what about other staff members...
1351 //return $this->company_id == $au->company_id;
1355 // yes, only owner company can mess with this...
1361 // extra case change passwod?
1362 case 'P': //??? password
1363 // standard perms -- for editing + if the user is dowing them selves..
1364 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1365 return $ret || $au->id == $this->id;
1368 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1374 function beforeInsert($req, $roo)
1376 $p = DB_DataObject::factory('core_person');
1377 if ($roo->authUser->id > -1 || $p->count() > 1) {
1380 $c = DB_DataObject::Factory('core_company');
1383 if (!$tc || $tc> 1) {
1384 $roo->jerr("can not create initial user as multiple companies already exist");
1387 $this->company_id = $c->id;
1388 $this->email = trim($this->email);
1392 function onInsert($req, $roo)
1395 $p = DB_DataObject::factory('core_person');
1396 if ($roo->authUser->id < 0 && $p->count() == 1) {
1397 // this seems a bit risky...
1399 $g = DB_DataObject::factory('core_group');
1403 $g->get('name', 'Administrators');
1405 $p = DB_DataObject::factory('core_group_member');
1406 $p->group_id = $g->id;
1407 $p->user_id = $this->id;
1410 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1414 if (!empty($req['project_id_addto'])) {
1415 $pd = DB_DataObject::factory('ProjectDirectory');
1416 $pd->project_id = $req['project_id_addto'];
1417 $pd->person_id = $this->id;
1419 $pd->office_id = $this->office_id;
1420 $pd->company_id = $this->company_id;
1426 function importFromArray($roo, $persons, $opts)
1428 if (empty($opts['prefix'])) {
1429 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1432 if (!is_array($persons) || empty($persons)) {
1433 $roo->jerr("error in the person data. - empty on not valid");
1435 DB_DataObject::factory('core_group')->initGroups();
1437 foreach($persons as $person){
1438 $p = DB_DataObject::factory('core_person');
1439 if($p->get('name', $person['name'])){
1442 $p->setFrom($person);
1444 $companies = DB_DataObject::factory('core_company');
1445 if(!$companies->get('comptype', 'OWNER')){
1446 $roo->jerr("Missing OWNER companies!");
1448 $p->company_id = $companies->pid();
1449 // strip the 'spaces etc.. make lowercase..
1450 $name = strtolower(str_replace(' ', '', $person['name']));
1451 $p->setPassword("{$opts['prefix']}{$name}");
1454 // if $person->groups is set.. then
1455 // add this person to that group eg. groups : [ 'Administrator' ]
1456 if(!empty($person['groups'])){
1457 $groups = DB_DataObject::factory('core_group');
1458 if(!$groups->get('name', $person['groups'])){
1459 $roo->jerr("Missing groups : {$person['groups']}");
1461 $gm = DB_DataObject::factory('core_group_member');
1462 $gm->change($p, $groups, true);
1465 $p->onInsert(array(), $roo);
1469 // this is for the To: "{getEmailName()}" <email@address>
1470 // not good for Dear XXXX, - use {person.firstname} for that.
1471 function getEmailName()
1475 if(!empty($this->honor)){
1476 array_push($name, $this->honor);
1479 if(!empty($this->name)){
1480 array_push($name, $this->name);
1482 return implode(' ', $name);
1485 if(!empty($this->firstname) || !empty($this->lastname)){
1486 array_push($name, $this->firstname);
1487 array_push($name, $this->lastname);
1489 $name = array_filter($name);
1491 return implode(' ', $name);
1494 return $this->email;
1497 function sesPrefix()
1499 $ff= HTML_FlexyFramework::get();
1501 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1503 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1505 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1510 function loginPublic() // used where???
1512 $this->isAuth(); // force session start..
1514 $db = $this->getDatabaseConnection();
1516 $ff = HTML_FlexyFramework::get();
1518 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1522 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1524 $p = DB_DAtaObject::Factory($this->tableName());
1525 $p->get($this->pid());
1527 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1532 function beforeUpdate($old, $q, $roo)
1534 $this->email = trim($this->email);
1537 function generateOathKey()
1539 require 'Base32.php';
1541 $base32 = new Base32();
1543 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1546 function generateQRCode($hash)
1549 empty($this->email) &&
1555 $issuer = rawurlencode($this->qrCodeIssuer());
1557 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1559 require_once 'Image/QRCode.php';
1561 $qrcode = new Image_QRCode();
1563 $image = $qrcode->makeCode($uri, array(
1564 'output_type' => 'return'
1569 $base64 = base64_encode(ob_get_contents());
1572 return "data:image/png;base64,{$base64}";
1575 function qrCodeIssuer()
1577 $pg= HTML_FlexyFramework::get()->page;
1579 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1584 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1586 $ff = HTML_FlexyFramework::get();
1587 $person = DB_DataObject::Factory('core_person');
1591 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1592 'person' => $person,
1593 'authFrom' => 'FAKE_LINK',
1594 'authKey' => 'FAKE_KEY',
1596 'rcpts' => $to->email,