6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
22 class Pman extends HTML_FlexyFramework_Page
25 var $appShortName= "";
26 var $appVersion = "1.8";
38 * ------------- Standard getAuth/get/post methods of framework.
43 function getAuth() // everyone allowed in!!!!!
45 $this->loadOwnerCompany();
53 if (isset($this->_hasInit)) {
56 $this->_hasInit = true;
58 $boot = HTML_FlexyFramework::get();
59 // echo'<PRE>';print_R($boot);exit;
60 $this->appName= $boot->appName;
61 $this->appNameShort= $boot->appNameShort;
62 $this->appModules= $boot->enable;
63 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
64 $this->appDisable = $boot->disable;
65 $this->version = $boot->version;
72 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
73 $bits = explode('/', $base);
75 if ($bits[0] == 'Link') {
76 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
77 header('Content-type: text/html; charset=utf-8');
80 if ($bits[0] == 'PasswordReset') {
81 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
82 header('Content-type: text/html; charset=utf-8');
87 if ($this->getAuthUser()) {
88 $this->addEvent("RELOAD");
93 $this->addEvent("BADURL", false, $base);
94 $this->jerr("invalid url");
97 if (isset($_GET['onloadTrack'])) {
98 $this->onloadTrack = (int)$_GET['onloadTrack'];
100 // getting this to work with xhtml is a nightmare
101 // = nbsp / <img> issues screw everyting up.
103 // force regeneration on load for development enviroments..
104 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
106 //header('Content-type: application/xhtml+xml; charset=utf-8');
107 header('Content-type: text/html; charset=utf-8');
110 function post($base) {
111 return $this->get($base);
115 * ------------- Authentication and permission info about logged in user!!!
120 function loadOwnerCompany()
122 $this->company = DB_DataObject::Factory('Companies');
123 if ($this->company) { // non-core pman projects
126 $this->company->get('comptype', 'OWNER');
129 function staticGetAuthUser()
131 $ff = HTML_FlexyFramework::get();
132 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
134 $u = DB_DataObject::factory($tbl);
138 return $u->getAuthUser();
140 function getAuthUser()
142 if (!empty($this->authUser)) {
143 return $this->authUser;
145 $ff = HTML_FlexyFramework::get();
146 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
148 $u = DB_DataObject::factory( $tbl );
152 $this->authUser =$u->getAuthUser();
153 return $this->authUser ;
155 function hasPerm($name, $lvl) // do we have a permission
157 static $pcache = array();
158 $au = $this->getAuthUser();
159 return $au->hasPerm($name,$lvl);
162 function hasModule($name)
165 if (!strpos( $name,'.') ) {
166 // use enable / disable..
169 $enabled = array('Core') ;
170 $enabled = !empty($this->appModules) ?
171 array_merge($enabled, explode(',', $this->appModules)) :
173 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
177 return in_array($name, $enabled) && !in_array($name, $disabled);
180 $x = DB_DataObject::factory('Group_Rights');
181 $ar = $x->defaultPermData();
182 if (empty($ar[$name]) || empty($ar[$name][0])) {
192 * ---------------- Global Tools ---------------
198 * send a template to the user
199 * rcpts are read from the resulting template.
201 * @arg $templateFile - the file in mail/XXXXXX.txt
202 * @arg $args - variables available to the form as {t.*} over and above 'this'
207 function sendTemplate($templateFile, $args)
212 $content = clone($this);
214 foreach((array)$args as $k=>$v) {
217 $content->msgid = md5(time() . rand());
219 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
220 /* use the regex compiler, as it doesnt parse <tags */
221 require_once 'HTML/Template/Flexy.php';
222 $template = new HTML_Template_Flexy( array(
223 'compiler' => 'Regex',
224 'filters' => array('SimpleTags','Mail'),
228 // this should be done by having multiple template sources...!!!
230 $template->compile('mail/'. $templateFile.'.txt');
232 /* use variables from this object to ouput data. */
233 $mailtext = $template->bufferedOutputObject($content);
234 //echo "<PRE>";print_R($mailtext);
236 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
237 require_once 'Mail/mimeDecode.php';
238 require_once 'Mail.php';
240 $decoder = new Mail_mimeDecode($mailtext);
241 $parts = $decoder->getSendArray();
242 if (PEAR::isError($parts)) {
244 //echo "PROBLEM: {$parts->message}";
247 list($recipents,$headers,$body) = $parts;
248 ///$recipents = array($this->email);
249 $mailOptions = PEAR::getStaticProperty('Mail','options');
250 $mail = Mail::factory("SMTP",$mailOptions);
251 $headers['Date'] = date('r');
252 if (PEAR::isError($mail)) {
255 $oe = error_reporting(E_ALL ^ E_NOTICE);
256 $ret = $mail->send($recipents,$headers,$body);
257 error_reporting($oe);
263 function checkFileUploadError() // check for file upload errors.
266 empty($_FILES['File'])
267 || empty($_FILES['File']['name'])
268 || empty($_FILES['File']['tmp_name'])
269 || empty($_FILES['File']['type'])
270 || !empty($_FILES['File']['error'])
271 || empty($_FILES['File']['size'])
273 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
279 * generate a tempory file with an extension (dont forget to delete it)
282 function tempName($ext)
284 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
286 return $x .'.'. $ext;
289 * ------------- Authentication testing ------ ??? MOVEME?
293 function linkAuth($trid, $trkey)
295 $tr = DB_DataObject::factory('Documents_Tracking');
296 if (!$tr->get($trid)) {
297 return "Invalid URL";
299 if (strtolower($tr->authkey) != strtolower($trkey)) {
300 $this->AddEvent("ERROR-L", false, "Invalid Key");
301 return "Invalid KEY";
304 $this->onloadTrack = (int) $tr->doc_id;
305 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
306 $this->AddEvent("ERROR-L", false, "Key Expired");
307 return "Key Expired";
309 // user logged in and not
310 $au = $this->getAuthUser();
311 if ($au && $au->id && $au->id != $tr->person_id) {
314 return "Logged Out existing Session\n - reload to log in with correct key";
316 if ($au) { // logged in anyway..
317 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
318 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
323 // authenticate the user...
325 $u = DB_DataObject::factory('Person');
327 $u->get($tr->person_id);
329 $this->AddEvent("LOGIN", false, "With Key");
331 // we need to redirect out - otherwise refererer url will include key!
332 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
344 * ------------- Authentication password reset ------ ??? MOVEME?
350 function resetPassword($id,$t, $key)
353 $au = $this->getAuthUser();
355 return "Already Logged in - no need to use Password Reset";
358 $u = DB_DataObject::factory('Person');
359 //$u->company_id = $this->company->id;
361 if (!$u->get($id) || !strlen($u->passwd)) {
366 if ($key != $u->genPassKey($t)) {
367 return "invalid key";
370 $u->no_reset_sent = 0;
373 if ($t < strtotime("NOW - 1 DAY")) {
376 $this->showNewPass = implode("/", array($id,$t,$key));
382 * ---------------- Standard JSON outputers. - used everywhere
385 function jerr($str, $errors=array()) // standard error reporting..
387 require_once 'Services/JSON.php';
388 $json = new Services_JSON();
390 if (!empty($_REQUEST['returnHTML']) ||
391 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
393 header('Content-type: text/html');
394 echo "<HTML><HEAD></HEAD><BODY>";
395 echo $json->encodeUnsafe(array(
398 'message' => $str, // compate with exeption / loadexception.
400 'errors' => $errors ? $errors : true, // used by forms to flag errors.
401 'authFailure' => !empty($errors['authFailure']),
403 echo "</BODY></HTML>";
407 echo $json->encode(array(
411 'message' => $str, // compate with exeption / loadexception.
412 'errors' => $errors ? $errors : true, // used by forms to flag errors.
413 'authFailure' => !empty($errors['authFailure']),
421 require_once 'Services/JSON.php';
422 $json = new Services_JSON();
424 if (!empty($_REQUEST['returnHTML']) ||
425 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
428 header('Content-type: text/html');
429 echo "<HTML><HEAD></HEAD><BODY>";
430 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
431 echo "</BODY></HTML>";
436 echo $json->encode(array('success'=> true, 'data' => $str));
441 * output data for grids or tree
442 * @ar {Array} ar Array of data
443 * @total {Number|false} total number of records (or false to return count(ar)
444 * @extra {Array} extra key value list of data to pass as extra data.
447 function jdata($ar,$total=false, $extra=array())
449 // should do mobile checking???
450 if ($total == false) {
453 $extra= $extra ? $extra : array();
454 require_once 'Services/JSON.php';
455 $json = new Services_JSON();
456 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
467 * ---------------- Page output?!?!?
471 function hasBg($fn) // used on front page to check if logos exist..
473 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
476 function outputJavascriptIncludes() // includes on devel version..
479 $mods = explode(',', $this->appModules);
480 array_unshift($mods, 'Core');
481 $mods = array_unique($mods);
484 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
486 foreach($mods as $mod) {
487 // add the css file..
488 if (in_array($mod, $disabled)) {
493 $files = $this->moduleJavascriptList($mod.'/widgets');
494 foreach($files as $f) {
495 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
498 $files = $this->moduleJavascriptList($mod);
499 foreach($files as $f) {
500 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
507 function outputCSSIncludes() // includes on CSS links.
510 $mods = explode(',', $this->appModules);
511 array_unshift($mods, 'Core');
512 $mods = array_unique($mods);
514 foreach($mods as $mod) {
515 // add the css file..
516 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
517 if (file_exists( $css)){
518 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
519 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
530 function moduleJavascriptList($mod)
533 $ff = HTML_FlexyFramework::get();
535 $dir = $this->rootDir.'/Pman/'. $mod;
537 $path = $this->rootURL."/Pman/$mod/";
538 $base = dirname($_SERVER['SCRIPT_FILENAME']);
539 $cfile = realpath($base .'/_compiled_/' . $mod);
540 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
542 if (!file_exists($dir)) {
550 if (file_exists($cfile)) {
551 // $ctime = max(filemtime($cfile), filectime($cfile));
552 // otherwise use compile dfile..
553 $cfile = basename(array_pop(glob($cfile . '/' . $mod . '*.js')));
555 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
556 if (file_exists($lfile)) {
557 array_push($files, $this->rootURL."/_translations_/$mod.js");
561 // works out if stuff has been updated..
562 // technically the non-dev version should output compiled only?!!?
564 while (false !== ($f = readdir($dh))) {
566 if (!preg_match('/\.js$/', $f)) {
569 // got the 'module file..'
571 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
572 $files[] = $path . $f;
577 // var_dump(array($maxtime , $ctime));
578 //if ($maxtime > $ctime) {
579 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
580 usort($files, $lsort);
581 // if (file_exists($lfile)) {
582 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
593 * ---------------- Logging ---------------
600 function addEvent($act, $obj = false, $remarks = '') {
601 $au = $this->getAuthUser();
602 $e = DB_DataObject::factory('Events');
604 if (is_a($e, 'PEAR_Error')) {
605 return; // no event table!
607 $e->person_name = $au ? $au->name : '';
608 $e->person_id = $au ? $au->id : '';
609 $e->event_when = date('Y-m-d H:i:s');
610 $e->ipaddr = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'cli';
612 $e->on_table = $obj ? $obj->tableName() : '';
614 $pk = $obj ? $obj->keys() : false;
616 $e->on_id = $obj && $pk ? $obj->{$pk[0]}: 0;
617 $e->remarks = $remarks;