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;
53 /* the code above is auto generated do not remove the tag below */
56 static $authUser = false;
61 // this might be a Person in some old code?
62 $p = DB_DataObject::Factory('core_person');
63 $p->get($this->owner_id);
72 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
78 function buildMail($templateFile, $args)
81 $args = (array) $args;
82 $content = clone($this);
84 foreach((array)$args as $k=>$v) {
88 $ff = HTML_FlexyFramework::get();
91 //?? is this really the place for this???
94 empty($args['no_auth']) &&
95 !in_array($templateFile, array(
96 // templates that can be sent without authentication.
102 $content->authUser = $this->getAuthUser();
103 if (!$content->authUser) {
104 return PEAR::raiseError("Not authenticated");
108 // should handle x-forwarded...
110 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111 $_SERVER["HTTP_HOST"] :
112 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
114 /* use the regex compiler, as it doesnt parse <tags */
117 'compiler' => 'Flexy',
119 'filters' => array('SimpleTags','Mail'),
125 if (!empty($args['templateDir'])) {
126 $tops['templateDir'] = $args['templateDir'];
131 require_once 'HTML/Template/Flexy.php';
132 $template = new HTML_Template_Flexy( $tops );
133 $template->compile("mail/$templateFile.txt");
135 /* use variables from this object to ouput data. */
136 $mailtext = $template->bufferedOutputObject($content);
139 // if a html file with the same name exists, use that as the body
140 // I've no idea where this code went, it was here before..
141 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142 $tops['nonHTML'] = false;
143 $template = new HTML_Template_Flexy( $tops );
144 $template->compile("mail/$templateFile.html");
145 $htmlbody = $template->bufferedOutputObject($content);
151 //echo "<PRE>";print_R($mailtext);
152 //print_R($mailtext);exit;
153 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154 require_once 'Mail/mimeDecode.php';
155 require_once 'Mail.php';
157 $decoder = new Mail_mimeDecode($mailtext);
158 $parts = $decoder->getSendArray();
160 if (is_a($parts,'PEAR_Error')) {
162 //echo "PROBLEM: {$parts->message}";
165 list($recipents,$headers,$body) = $parts;
166 $recipents = array($this->email);
167 if (!empty($content->bcc) && is_array($content->bcc)) {
168 $recipents =array_merge($recipents, $content->bcc);
170 $headers['Date'] = date('r');
172 if ($htmlbody !== false) {
173 require_once 'Mail/mime.php';
174 $mime = new Mail_mime(array('eol' => "\n"));
175 $mime->setTXTBody($body);
176 $mime->setHTMLBody($htmlbody);
177 // I think there might be code in mediaoutreach toEmail somewhere
178 // h embeds images here..
179 $body = $mime->get();
180 $headers = $mime->headers($headers);
184 'recipients' => $recipents,
185 'headers' => $headers,
193 * - user must be authenticate or args[no_auth] = true
194 * or template = password_[reset|welcome]
197 function sendTemplate($templateFile, $args)
199 $ar = $this->buildMail($templateFile, $args);
201 //print_r($recipents);exit;
202 $mailOptions = PEAR::getStaticProperty('Mail','options');
203 $mail = Mail::factory("SMTP",$mailOptions);
205 if (PEAR::isError($mail)) {
208 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210 error_reporting($oe);
218 function getEmailFrom()
220 if (empty($this->name)) {
224 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
227 function toEventString()
229 return empty($this->name) ? $this->email : $this->name;
232 function verifyAuth()
234 $ff= HTML_FlexyFramework::get();
235 if (!empty($ff->Pman['auth_comptype']) &&
236 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
239 $sesPrefix = $this->sesPrefix();
241 self::$authUser = false;
242 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
246 //$ff->page->jerr("Login not permited to outside companies");
253 // ---------------- authentication / passwords and keys stuff ----------------
256 // do not start a session if we are using http auth...
257 // we have a situation where the app is behind a http access and is also login
258 // need to work out a way to handle that.
260 $session_started = false;
261 if (php_sapi_name() != "cli" && empty($_SERVER['PHP_AUTH_USER']) && empty($_COOKIE['PHPSESSID'])) {
262 $session_started = false;
268 $ff= HTML_FlexyFramework::get();
270 $sesPrefix = $this->sesPrefix();
272 if (self::$authUser) {
273 return self::$authUser;
277 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
279 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
280 $u = DB_DataObject::factory($this->tableName());
282 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
283 if ($u->verifyAuth()) {
284 self::$authUser = $u;
288 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
289 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
290 setcookie('Pman.timeout', -1, time() + (30*60), '/');
295 $u = DB_DataObject::factory($this->tableName());
297 if (empty($_COOKIE['PHPSESSID']) // http auth requests should not have this...
299 !empty($_SERVER['PHP_AUTH_USER'])
301 !empty($_SERVER['PHP_AUTH_PW'])
303 $u->get('email', $_SERVER['PHP_AUTH_USER'])
305 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
307 // logged in via http auth
308 // http auth will not need session...
309 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
310 self::$authUser = $u;
314 // at this point all http auth stuff is done, so we can init session
315 if (php_sapi_name() != "cli" && !$session_started) {
320 if (!$this->canInitializeSystem()) {
321 // die("can not init");
326 $auto_auth_allow = false;
327 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
328 $auto_auth_allow = true;
330 if ( !empty($ff->Pman['local_autoauth'])
332 !empty($_SERVER['SERVER_ADDR']) &&
333 !empty($_SERVER['REMOTE_ADDR']) &&
336 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
337 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
341 $_SERVER['SERVER_ADDR'] == '::1' &&
342 $_SERVER['REMOTE_ADDR'] == '::1'
347 $auto_auth_allow = true;
351 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
352 $auto_auth_allow = false;
354 //var_dump($auto_auth_allow);
356 $default_admin = false;
357 if ($auto_auth_allow) {
358 $group = DB_DataObject::factory('core_group');
359 $group->get('name', 'Administrators');
361 $member = DB_DataObject::factory('core_group_member');
363 $member->group_id = $group->id;
365 join_user_id_id.id IS NOT NULL
367 if($member->find(true)){
368 $default_admin = DB_DataObject::factory($this->tableName());
369 $default_admin->autoJoin();
370 if(!$default_admin->get($member->user_id)){
371 $default_admin = false;
376 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
377 $u = DB_DataObject::factory($this->tableName());
379 $ff = HTML_FlexyFramework::get();
381 if ($auto_auth_allow &&
382 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
385 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
387 // if we request other URLS.. then we get auto logged in..
388 self::$authUser = $default_admin ? $default_admin : $u;;
389 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
393 //var_dump(session_id());
394 //var_dump($_SESSION[__CLASS__]);
396 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
399 //die("got this far?");
400 // not in session or not matched...
401 $u = DB_DataObject::factory($this->tableName());
402 $u->whereAdd(' LENGTH(passwd) > 0');
404 if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) {
405 $_SESSION[get_class($this)] = array();
407 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
408 if (class_exists('PEAR')) {
409 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
411 die($error->toString()); // not really a good thing to do...
414 if (!$n){ // authenticated as there are no users in the system...
421 function canInitializeSystem()
424 return !strcasecmp(get_class($this) , __CLASS__);
427 function getAuthUser()
429 if (!$this->isAuth()) {
433 $ff= HTML_FlexyFramework::get();
435 $sesPrefix = $this->sesPrefix();
437 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
439 if (self::$authUser) {
441 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
442 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
443 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
445 // not really sure why it's cloned..
446 return clone (self::$authUser);
453 if (!$this->canInitializeSystem()) {
459 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
460 $u = DB_DataObject::factory($this->tableName());
461 $u->whereAdd(' LENGTH(passwd) > 0');
462 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
467 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
468 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
471 // fake person - open system..
472 //$ce = DB_DataObject::factory('core_enum');
476 $u = DB_DataObject::factory($this->tableName());
479 // if a company has been created fill that in in company_id_id
480 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
482 $u->company_id_id = $c->pid();
483 $u->company_id = $c->pid();
493 $this->isAuth(); // force session start..
494 if (!$this->verifyAuth()) { // check for company valid..
498 // open up iptables at login..
499 $dbname = $this->databaseNickname();
500 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
502 // refresh admin group if we are logged in as one..
503 //DB_DataObject::debugLevel(1);
504 $g = DB_DataObject::factory('core_group');
506 $g->get('name', 'Administrators');
507 $gm = DB_DataObject::Factory('core_group_member');
508 if (in_array($g->id,$gm->listGroupMembership($this))) {
509 // refresh admin groups.
510 $gr = DB_DataObject::Factory('core_group_right');
511 $gr->applyDefs($g, 0);
514 $sesPrefix = $this->sesPrefix();
516 // we should not store the whole data in the session - otherwise it get's huge.
517 $p = DB_DAtaObject::Factory($this->tableName());
518 $p->get($this->pid());
522 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
523 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
525 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
526 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
528 $pp = DB_DAtaObject::Factory($this->tableName());
529 $pp->get($this->pid());
532 self::$authUser = $pp;
533 // ensure it's written so that ajax calls can fetch it..
540 $this->isAuth(); // force session start..
542 $sesPrefix = $this->sesPrefix();
543 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
544 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
545 self::$authUser = false;
548 function genPassKey ($t)
550 return md5($this->email . $t. $this->passwd);
552 function simpleAuthKey($m = 0)
554 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
556 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
559 * When we generate autologin urls:
560 * eg. /Somesite/Test/12
562 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
564 * eg. genAutoLoginURL($sub, $expires)
566 function genAutoLoginURL($url, $expires = false)
568 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
569 //echo serialize(array($url, $expires, $this->email, $this->passwd));
570 //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
572 return $url.'/'.$this->id .'/'.$expires.'/'.
575 array($url, $expires, $this->email,$this->passwd)
581 function validateAutoLogin($called)
583 $bits = explode("/",$called);
584 if (count($bits) < 4) {
585 return false; // unrelated.
587 $hash = array_pop($bits);
588 $time = array_pop($bits);
590 $id = array_pop($bits);
591 if (!is_numeric($time) || !is_numeric($id)) {
592 return false; // wrong format.
594 $u = DB_DataObject::Factory($this->tableName());
596 $url = implode("/", $bits);
597 if ($time < time()) {
600 //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
601 //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
602 if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
610 function checkTwoFactorAuthentication($val)
614 // also used in login
615 require_once 'System.php';
619 empty($this->oath_key)
624 $oathtool = System::which('oathtool');
630 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
632 $password = exec($cmd);
634 return ($password == $val) ? true : false;
637 function checkPassword($val)
639 if (substr($this->passwd,0,1) == '$') {
640 if (function_exists('pasword_verify')) {
641 return password_verify($val, $this->passwd);
643 return crypt($val,$this->passwd) == $this->passwd ;
645 // old style md5 passwords...- cant be used with courier....
646 return md5($val) == $this->passwd;
649 function setPassword($value)
651 if (function_exists('pasword_hash')) {
652 return password_hash($value);
656 while(strlen($salt)<9) {
657 $salt.=chr(rand(64,126));
658 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
660 $this->passwd = crypt($value, '$1$'. $salt. '$');
665 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
667 require_once 'Text/Password.php';
668 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
669 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
670 $this->setPassword($this->rawPasswd);
671 return $this->rawPasswd;
676 if (empty($this->company_id)) {
679 $x = DB_DataObject::factory('core_company');
681 $x->get($this->company_id);
684 function loadCompany()
686 $this->company = $this->company();
691 return $this->active;
693 function authUserName($n) // set username prior to acheck user exists query.
696 $this->whereAdd('LENGTH(passwd) > 1');
701 if (!func_num_args()) {
704 $ar = func_get_args();
705 $val = array_shift($ar);
706 if ($val == $this->lang) {
716 function authUserArray()
718 $aur = $this->toArray();
724 //DB_DataObject::debugLevel(1);
725 $c = DB_Dataobject::factory('core_company');
726 $im = DB_Dataobject::factory('Images');
727 $c->joinAdd($im, 'LEFT');
729 $c->selectAs($c, 'company_id_%s');
730 $c->selectAs($im, 'company_id_logo_id_%s');
731 $c->id = $this->company_id;
735 $aur = array_merge( $c->toArray(),$aur);
737 if (empty($c->company_id_logo_id_id)) {
739 $im = DB_Dataobject::factory('Images');
740 $im->ontable = DB_DataObject::factory('core_company')->tableName();
742 $im->imgtype = 'LOGO';
745 $im->selectAs($im, 'company_id_logo_id_%s');
746 if ($im->find(true)) {
748 foreach($im->toArray() as $k=>$v) {
749 if (!preg_match('/^company_id_logo_id_/', $k)) {
758 $aur['perms'] = $this->getPerms();
759 $g = DB_DataObject::Factory('core_group_member');
760 $aur['groups'] = $g->listGroupMembership($this, 'name');
763 $aur['dailykey'] = '';
764 $aur['oath_key'] = '';
766 $aur['oath_key_enable'] = !empty($this->oath_key);
767 $aur['require_oath'] = 1;
769 $s = DB_DataObject::Factory('core_setting');
770 $oath_require = $s->lookup('core', 'two_factor_auth_required');
771 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
773 $aur['core_person_settings'] = array();
775 $core_person_settings = DB_DataObject::factory('core_person_settings');
776 $core_person_settings->setFrom(array(
777 'person_id' => $this->id
780 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
785 // ----------PERMS------ ----------------
788 //DB_DataObject::debugLevel(1);
789 // find out all the groups they are a member of.. + Default..
791 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
793 $g = DB_DataObject::Factory('core_group_right');
799 return $g->adminRights(); // system is not set up - so they get full rights.
801 //DB_DataObject::debugLevel(1);
802 $g = DB_DataObject::Factory('core_group_member');
803 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
805 // add the current user to the admin group..
806 $g = DB_DataObject::Factory('core_group');
807 if ($g->get('name', 'Administrators')) {
808 $gm = DB_DataObject::Factory('core_group_member');
809 $gm->group_id = $g->id;
810 $gm->user_id = $this->id;
816 // ------ STANDARD PERMISSION HANDLING.
817 $isOwner = $this->company()->comptype == 'OWNER';
818 $g = DB_DataObject::Factory('core_group_member');
819 $grps = $g->listGroupMembership($this);
821 $isAdmin = $g->inAdmin; //??? what???
822 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
823 // the load all the perms for those groups, and add them all together..
824 // then load all those
825 $g = DB_DataObject::Factory('core_group_right');
826 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
827 //echo '<PRE>';print_r($ret);
833 *Basic group fetching - probably needs to filter by type eventually.
835 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
838 function groups($what=false)
840 $g = DB_DataObject::Factory('core_group_member');
841 $grps = $g->listGroupMembership($this);
842 $g = DB_DataObject::Factory('core_group');
843 $g->whereAddIn('id', $grps, 'int');
844 return $g->fetchAll($what);
850 function hasPerm($name, $lvl)
852 static $pcache = array();
854 if (!isset($pcache[$this->id])) {
855 $pcache[$this->id] = $this->getPerms();
858 // echo "<PRE>";print_r($pcache[$au->id]);
859 // var_dump($pcache[$au->id]);
860 if (empty($pcache[$this->id][$name])) {
864 return strpos($pcache[$this->id][$name], $lvl) > -1;
868 // ------------ROO HOOKS------------------------------------
869 function applyFilters($q, $au, $roo)
871 //DB_DataObject::DebugLevel(1);
872 if(!empty($q['_to_qr_code'])){
873 $person = DB_DataObject::factory('Core_person');
874 $person->id = $q['id'];
876 if(!$person->find(true)) {
877 $roo->jerr('_invalid_person');
880 $hash = $this->generateOathKey();
882 $_SESSION[__CLASS__] =
883 isset($_SESSION[__CLASS__]) ?
884 $_SESSION[__CLASS__] : array();
885 $_SESSION[__CLASS__]['oath'] =
886 isset($_SESSION[__CLASS__]['oath']) ?
887 $_SESSION[__CLASS__]['oath'] : array();
889 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
891 $qrcode = $person->generateQRCode($hash);
894 $roo->jerr('Fail to generate QR Code');
900 'issuer' => $person->qrCodeIssuer()
904 if(!empty($q['two_factor_auth_code'])) {
905 $person = DB_DataObject::factory('core_person');
906 $person->get($q['id']);
908 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
910 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
912 unset($_SESSION[__CLASS__]['oath'][$person->id]);
916 $roo->jerr('_invalid_auth_code');
919 if(!empty($q['oath_key_disable'])) {
920 $person = DB_DataObject::factory('core_person');
921 $person->get($q['id']);
925 $person->oath_key = '';
931 if (!empty($q['query']['is_owner'])) {
932 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
935 if (!empty($q['query']['person_not_internal'])) {
936 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
939 if (!empty($q['query']['person_internal_only_all'])) {
942 // must be internal and not current user (need for distribution list)
943 // user has a projectdirectory entry and role is not blank.
944 //DB_DataObject::DebugLevel(1);
945 $pd = DB_DataObject::factory('ProjectDirectory');
946 $pd->whereAdd("role != ''");
948 $pd->selectAdd('distinct(person_id) as person_id');
949 $roled = $pd->fetchAll('person_id');
951 {$this->tableName()}.id IN (".implode(',', $roled) . ")
953 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
956 // -- for distribution
957 if (!empty($q['query']['person_internal_only'])) {
958 // must be internal and not current user (need for distribution list)
959 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
961 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
962 // ".id != ".$au->id);
963 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
966 if (!empty($q['query']['comptype_or_company_id'])) {
967 // DB_DataObject::debugLevel(1);
968 $bits = explode(',', $q['query']['comptype_or_company_id']);
969 $id = (int) array_pop($bits);
970 $ct = $this->escape($bits[0]);
972 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
978 if (!empty($q['query']['person_inactive'])) {
979 // DB_Dataobject::debugLevel(1);
982 $tn_p = $this->tableName();
983 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
984 $tn_g = DB_DataObject::Factory('core_group')->tableName();
986 ///---------------- Group views --------
987 if (!empty($q['query']['in_group'])) {
988 // DB_DataObject::debugLevel(1);
989 $ing = (int) $q['query']['in_group'];
990 if ($q['query']['in_group'] == -1) {
992 // list all staff who are not in a group.
993 $this->whereAdd("{$this->tableName()}.id NOT IN (
994 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
995 $tn_g ON $tn_g.id = $tn_gm.group_id)");
999 $this->whereAdd("$tn_p.id IN (
1000 SELECT distinct(user_id) FROM $tn_gm
1001 WHERE group_id = $ing
1007 if(!empty($q['in_group_name'])){
1009 $v = $this->escape($q['in_group_name']);
1014 DISTINCT(user_id) FROM $tn_gm
1018 $tn_g.id = $tn_gm.group_id
1024 if(!empty($q['in_group_starts'])){
1026 $v = $this->escape($q['in_group_starts']);
1031 DISTINCT(user_id) FROM $tn_gm
1035 $tn_g.id = $tn_gm.group_id
1037 $tn_g.name LIKE '{$v}%'
1044 // #2307 Search Country!!
1045 if (!empty($q['query']['in_country'])) {
1046 // DB_DataObject::debugLevel(1);
1047 $inc = $q['query']['in_country'];
1048 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1051 if (!empty($q['query']['not_in_directory'])) {
1052 // it's a Person list..
1053 // DB_DATaobjecT::debugLevel(1);
1055 // specific to project directory which is single comp. login
1057 $owncomp = DB_DataObject::Factory('core_company');
1058 $owncomp->get('comptype', 'OWNER');
1059 if ($q['company_id'] == $owncomp->id) {
1065 if ( $q['query']['not_in_directory'] > -1) {
1066 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1067 // can list current - so that it does not break!!!
1068 $this->whereAdd("$tn_p.id NOT IN
1069 ( SELECT distinct person_id FROM $tn_pd WHERE
1070 project_id = " . $q['query']['not_in_directory'] . " AND
1071 company_id = " . $this->company_id . ')');
1075 if (!empty($q['query']['role'])) {
1076 // it's a Person list..
1077 // DB_DATaobjecT::debugLevel(1);
1079 // specific to project directory which is single comp. login
1081 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1082 // can list current - so that it does not break!!!
1083 $this->whereAdd("$tn_p.id IN
1084 ( SELECT distinct person_id FROM $tn_pd WHERE
1085 role = '". $this->escape($q['query']['role']) ."'
1091 if (!empty($q['query']['project_member_of'])) {
1092 // this is also a flag to return if they are a member..
1093 //DB_DataObject::debugLevel(1);
1094 $do = DB_DataObject::factory('ProjectDirectory');
1095 $do->project_id = $q['query']['project_member_of'];
1096 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1097 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1098 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1101 if (!empty($q['query']['project_member_filter'])) {
1102 $this->having('is_member !=0');
1108 if(!empty($q['query']['name'])){
1110 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1114 if(!empty($q['query']['name_or_email'])){
1115 $v = $this->escape($q['query']['name_or_email']);
1117 {$this->tableName()}.name LIKE '%{$v}%'
1119 {$this->tableName()}.email LIKE '%{$v}%'
1122 if(!empty($q['query']['name_starts'])){
1124 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1128 if (!empty($q['query']['search'])) {
1130 // use our magic search builder...
1132 require_once 'Text/SearchParser.php';
1133 $x = new Text_SearchParser($q['query']['search']);
1141 "join_company_id_id.name"
1143 $tbcols = $this->table();
1144 foreach(array('firstname','lastname') as $k) {
1145 if (isset($tbcols[$k])) {
1146 $props[] = "{$tn_p}.{$k}";
1153 $str = $x->toSQL(array(
1154 'default' => $props,
1156 'company' => 'join_company_id_id.name',
1157 //'country' => 'Clipping.country',
1158 // 'media' => 'Clipping.media_name',
1160 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1165 $this->whereAdd($str); /*
1166 $tn_p.name LIKE '%$s%' OR
1167 $tn_p.email LIKE '%$s%' OR
1168 $tn_p.role LIKE '%$s%' OR
1169 $tn_p.phone LIKE '%$s%' OR
1170 $tn_p.remarks LIKE '%$s%'
1175 // project directory rules -- this may distrupt things.
1176 $p = DB_DataObject::factory('ProjectDirectory');
1177 // if project directories are set up, then we can apply project query rules..
1180 $pids = $p->projects($au);
1181 if (isset($q['query']['project_id'])) {
1182 $pid = (int)$q['query']['project_id'];
1183 if (!in_array($pid, $pids)) {
1184 $roo->jerr("Project not in users valid projects");
1186 $pids = array($pid);
1189 //if (empty($q['_anyrole'])) { // should be project_directry_role
1190 // $p->whereAdd("{$p->tableName()}.role != ''");
1192 if (!empty($q['query']['role'])) { // should be project_directry_role
1193 $role = $this->escape($q['query']['role']);
1195 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1199 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1200 $peps = $p->people($pids);
1201 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1205 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1206 if (isset($q['query']['ticket_id'])) {
1207 // find out what state the ticket is in.
1208 $t = DB_DataObject::Factory('mtrack_ticket');
1210 $t->get($q['query']['ticket_id']);
1212 if (!$this->checkPerm('S', $au)) {
1213 $roo->jerr("permssion denied to query state of ticket");
1216 $p = DB_DataObject::factory('ProjectDirectory');
1217 $pids = array($t->project_id);
1219 $peps = $p->people($pids);
1221 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1223 //$this->whereAdd('join_prole != ''");
1228 * Seems we never expose oath_key / passwd, so...
1231 if($this->tableName() == 'core_person'){
1232 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1235 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1236 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1239 if (isset($q['_with_group_membership'])) {
1240 $this->selectAddGroupMemberships();
1245 function selectAddGroupMemberships()
1251 GROUP_CONCAT( CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name END separator '\n')
1257 core_group.id = core_group_member.group_id
1259 core_group_member.user_id = core_person.id
1261 core_group.display_name ASC
1262 ), '') as member_of");
1265 function setFromRoo($ar, $roo)
1267 $this->setFrom($ar);
1269 if(!empty($ar['_enable_oath_key'])){
1270 $oath_key = $this->generateOathKey();
1273 if (!empty($ar['passwd1'])) {
1274 $this->setPassword($ar['passwd1']);
1278 ($this->email == $roo->old->email)&&
1279 ($this->company_id == $roo->old->company_id)
1283 if (empty($this->email)) {
1286 // this only applies to our owner company..
1287 $c = $this->company();
1288 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1293 $xx = DB_Dataobject::factory($this->tableName());
1295 'email' => $this->email,
1296 // 'company_id' => $x->company_id
1300 return "Duplicate Email found";
1307 * before Delete - delete significant dependancies..
1308 * this is called after checkPerm..
1311 function beforeDelete($dependants_array, $roo)
1313 //delete group membership except for admin group..
1314 // if they are a member of admin group do not delete anything.
1315 $default_admin = false;
1317 $e = DB_DataObject::Factory('Events');
1318 $e->whereAdd('person_id = ' . $this->id);
1320 $g = DB_DataObject::Factory('core_group');
1321 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1323 $p = DB_DataObject::Factory('core_group_member');
1325 'user_id' => $this->id,
1326 'group_id' => $g->id
1330 $roo->jerr("Please remove this user from the Administrator group before deleting");
1334 $p = DB_DataObject::Factory('core_group_member');
1335 $p->user_id = $this->id;
1336 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1337 $e->logDeletedRecord($mem);
1339 foreach($mem as $p) {
1343 $e = DB_DataObject::Factory('Events');
1344 $e->person_id = $this->id;
1345 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1347 $e->logDeletedRecord($eve);
1348 foreach($eve as $e) {
1359 * Check if the a user has access to modify this item.
1360 * @param String $lvl Level (eg. Core.Projects)
1361 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1362 * @param boolean $changes alllow changes???
1364 * @return false if no access..
1366 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1369 // do we have an empty system..
1370 if ($au && $au->id == -1) {
1373 // if not authenticated... do not allow in???
1378 // determine if it's staff!!!
1379 $owncomp = DB_DataObject::Factory('core_company');
1380 $owncomp->get('comptype', 'OWNER');
1381 $isStaff = ($au->company_id == $owncomp->id);
1386 // - can not change company!!!
1388 isset($changes['company_id']) &&
1389 $changes['company_id'] != $au->company_id) {
1392 // can only set new emails..
1394 !empty($this->email) &&
1395 isset($changes['email']) &&
1396 $changes['email'] != $this->email) {
1401 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1402 // ???? do we want this?
1404 // edit self... - what about other staff members...
1406 //return $this->company_id == $au->company_id;
1410 // yes, only owner company can mess with this...
1416 // extra case change passwod?
1417 case 'P': //??? password
1418 // standard perms -- for editing + if the user is dowing them selves..
1419 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1420 return $ret || $au->id == $this->id;
1423 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1429 function beforeInsert($req, $roo)
1431 $p = DB_DataObject::factory('core_person');
1432 if ($roo->authUser->id > -1 || $p->count() > 1) {
1435 $c = DB_DataObject::Factory('core_company');
1438 if (!$tc || $tc> 1) {
1439 $roo->jerr("can not create initial user as multiple companies already exist");
1442 $this->company_id = $c->id;
1443 $this->email = trim($this->email);
1447 function onInsert($req, $roo)
1450 $p = DB_DataObject::factory('core_person');
1451 if ($roo->authUser->id < 0 && $p->count() == 1) {
1452 // this seems a bit risky...
1454 $g = DB_DataObject::factory('core_group');
1458 $g->get('name', 'Administrators');
1460 $p = DB_DataObject::factory('core_group_member');
1461 $p->group_id = $g->id;
1462 $p->user_id = $this->id;
1465 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1469 if (!empty($req['project_id_addto'])) {
1470 $pd = DB_DataObject::factory('ProjectDirectory');
1471 $pd->project_id = $req['project_id_addto'];
1472 $pd->person_id = $this->id;
1474 $pd->office_id = $this->office_id;
1475 $pd->company_id = $this->company_id;
1481 function importFromArray($roo, $persons, $opts)
1483 if (empty($opts['prefix'])) {
1484 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1487 if (!is_array($persons) || empty($persons)) {
1488 $roo->jerr("error in the person data. - empty on not valid");
1490 DB_DataObject::factory('core_group')->initGroups();
1492 foreach($persons as $person){
1493 $p = DB_DataObject::factory('core_person');
1494 if($p->get('name', $person['name'])){
1497 $p->setFrom($person);
1499 $companies = DB_DataObject::factory('core_company');
1500 if(!$companies->get('comptype', 'OWNER')){
1501 $roo->jerr("Missing OWNER companies!");
1503 $p->company_id = $companies->pid();
1504 // strip the 'spaces etc.. make lowercase..
1505 $name = strtolower(str_replace(' ', '', $person['name']));
1506 $p->setPassword("{$opts['prefix']}{$name}");
1509 // if $person->groups is set.. then
1510 // add this person to that group eg. groups : [ 'Administrator' ]
1511 if(!empty($person['groups'])){
1512 $groups = DB_DataObject::factory('core_group');
1513 if(!$groups->get('name', $person['groups'])){
1514 $roo->jerr("Missing groups : {$person['groups']}");
1516 $gm = DB_DataObject::factory('core_group_member');
1517 $gm->change($p, $groups, true);
1520 $p->onInsert(array(), $roo);
1524 // this is for the To: "{getEmailName()}" <email@address>
1525 // not good for Dear XXXX, - use {person.firstname} for that.
1526 function getEmailName()
1530 if(!empty($this->honor)){
1531 array_push($name, $this->honor);
1534 if(!empty($this->name)){
1535 array_push($name, $this->name);
1537 return implode(' ', $name);
1540 if(!empty($this->firstname) || !empty($this->lastname)){
1541 array_push($name, $this->firstname);
1542 array_push($name, $this->lastname);
1544 $name = array_filter($name);
1546 return implode(' ', $name);
1549 return $this->email;
1552 function sesPrefix()
1554 $ff= HTML_FlexyFramework::get();
1556 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1558 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1560 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1565 function loginPublic() // used where???
1567 $this->isAuth(); // force session start..
1569 $db = $this->getDatabaseConnection();
1571 $ff = HTML_FlexyFramework::get();
1573 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1577 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1579 $p = DB_DAtaObject::Factory($this->tableName());
1580 $p->get($this->pid());
1582 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1587 function beforeUpdate($old, $q, $roo)
1589 $this->email = trim($this->email);
1592 function generateOathKey()
1594 require 'Base32.php';
1596 $base32 = new Base32();
1598 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1601 function generateQRCode($hash)
1604 empty($this->email) &&
1610 $issuer = rawurlencode($this->qrCodeIssuer());
1612 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1614 require_once 'Image/QRCode.php';
1616 $qrcode = new Image_QRCode();
1618 $image = $qrcode->makeCode($uri, array(
1619 'output_type' => 'return'
1624 $base64 = base64_encode(ob_get_contents());
1627 return "data:image/png;base64,{$base64}";
1630 function qrCodeIssuer()
1632 $pg= HTML_FlexyFramework::get()->page;
1634 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1639 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1641 $ff = HTML_FlexyFramework::get();
1642 $person = DB_DataObject::Factory('core_person');
1646 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1647 'person' => $person,
1648 'authFrom' => 'FAKE_LINK',
1649 'authKey' => 'FAKE_KEY',
1651 'rcpts' => $to->email,