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?!? ;)
20 * DB_DataObject*:*toEventString (for logging - this is generically prefixed to all database operations.)
21 * - any data object where this method exists, the result will get prefixed to the log remarks
24 class Pman extends HTML_FlexyFramework_Page
27 var $appShortName= "";
28 var $appVersion = "1.8";
35 var $appDisabled = array(); // array of disabled modules..
36 // (based on config option disable)
38 var $authUser; // always contains the authenticated user..
43 * ------------- Standard getAuth/get/post methods of framework.
48 function getAuth() // everyone allowed in!!!!!
50 $this->loadOwnerCompany();
58 if (isset($this->_hasInit)) {
61 $this->_hasInit = true;
63 $boot = HTML_FlexyFramework::get();
64 // echo'<PRE>';print_R($boot);exit;
65 $this->appName= $boot->appName;
66 $this->appNameShort= $boot->appNameShort;
67 $this->appModules= $boot->enable;
68 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
69 $this->appDisable = $boot->disable;
70 $this->appDisabled = explode(',', $boot->disable);
71 $this->version = $boot->version;
73 if (!empty($ff->Pman['local_autoauth']) &&
74 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
75 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
85 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
86 $bits = explode('/', $base);
88 if ($bits[0] == 'Link') {
89 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
90 header('Content-type: text/html; charset=utf-8');
93 if ($bits[0] == 'PasswordReset') {
94 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
95 header('Content-type: text/html; charset=utf-8');
100 if ($this->getAuthUser()) {
101 $this->addEvent("RELOAD");
106 $this->addEvent("BADURL", false, $base);
107 $this->jerr("invalid url");
110 if (isset($_GET['onloadTrack'])) {
111 $this->onloadTrack = (int)$_GET['onloadTrack'];
113 // getting this to work with xhtml is a nightmare
114 // = nbsp / <img> issues screw everyting up.
115 //var_dump($this->isDev);
116 // force regeneration on load for development enviroments..
118 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
120 //header('Content-type: application/xhtml+xml; charset=utf-8');
121 header('Content-type: text/html; charset=utf-8');
124 function post($base) {
125 return $this->get($base);
129 // --------------- AUTHENTICATION or system information
132 * finds the compay with comptype=='OWNER'
134 * @return {Pman_Core_DataObjects_Companies} the owner company
136 function loadOwnerCompany()
139 $this->company = DB_DataObject::Factory('Companies');
140 if ($this->company) { // non-core pman projects
143 $this->company->get('comptype', 'OWNER');
150 * getAuthUser: - get the authenticated user..
152 * @return {DB_DataObject} of type Pman[authTable] if authenticated.
155 function getAuthUser()
157 if (!empty($this->authUser)) {
158 return $this->authUser;
160 $ff = HTML_FlexyFramework::get();
161 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
163 $u = DB_DataObject::factory( $tbl );
167 $this->authUser =$u->getAuthUser();
168 return $this->authUser ;
172 * wrapper arround authuser->hasPerm
173 * @see Pman_Core_DataObjects_User::hasPerm
175 * @param {String} $name The permission name (eg. Projects.List)
176 * @param {String} $lvl eg. (C)reate (E)dit (D)elete ... etc.
179 function hasPerm($name, $lvl) // do we have a permission
181 static $pcache = array();
182 $au = $this->getAuthUser();
183 return $au && $au->hasPerm($name,$lvl);
188 * modulesList: List the modules in the application
190 * @return {Array} list of modules
192 function modulesList()
196 $mods = explode(',', $this->appModules);
197 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
198 array_unshift($mods, 'Core');
201 $mods = array_unique($mods);
203 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
205 foreach($mods as $mod) {
206 // add the css file..
207 if (in_array($mod, $disabled)) {
218 function hasModule($name)
221 if (!strpos( $name,'.') ) {
222 // use enable / disable..
223 return in_array($name, $this->modules());
226 $x = DB_DataObject::factory('Group_Rights');
227 $ar = $x->defaultPermData();
228 if (empty($ar[$name]) || empty($ar[$name][0])) {
239 * ---------------- Global Tools ---------------
245 * send a template to the user
246 * rcpts are read from the resulting template.
248 * @arg $templateFile - the file in mail/XXXXXX.txt
249 * @arg $args - variables available to the form as {t.*} over and above 'this'
254 function sendTemplate($templateFile, $args)
259 $content = clone($this);
261 foreach((array)$args as $k=>$v) {
264 $content->msgid = md5(time() . rand());
266 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
267 /* use the regex compiler, as it doesnt parse <tags */
268 require_once 'HTML/Template/Flexy.php';
269 $template = new HTML_Template_Flexy( array(
270 'compiler' => 'Regex',
271 'filters' => array('SimpleTags','Mail'),
275 // this should be done by having multiple template sources...!!!
277 $template->compile('mail/'. $templateFile.'.txt');
279 /* use variables from this object to ouput data. */
280 $mailtext = $template->bufferedOutputObject($content);
281 //echo "<PRE>";print_R($mailtext);
283 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
284 require_once 'Mail/mimeDecode.php';
285 require_once 'Mail.php';
287 $decoder = new Mail_mimeDecode($mailtext);
288 $parts = $decoder->getSendArray();
289 if (PEAR::isError($parts)) {
291 //echo "PROBLEM: {$parts->message}";
294 list($recipents,$headers,$body) = $parts;
295 ///$recipents = array($this->email);
296 $mailOptions = PEAR::getStaticProperty('Mail','options');
297 $mail = Mail::factory("SMTP",$mailOptions);
298 $headers['Date'] = date('r');
299 if (PEAR::isError($mail)) {
302 $oe = error_reporting(E_ALL ^ E_NOTICE);
303 $ret = $mail->send($recipents,$headers,$body);
304 error_reporting($oe);
310 function checkFileUploadError() // check for file upload errors.
313 empty($_FILES['File'])
314 || empty($_FILES['File']['name'])
315 || empty($_FILES['File']['tmp_name'])
316 || empty($_FILES['File']['type'])
317 || !empty($_FILES['File']['error'])
318 || empty($_FILES['File']['size'])
320 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
326 * generate a tempory file with an extension (dont forget to delete it)
329 function tempName($ext)
331 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
333 return $x .'.'. $ext;
336 * ------------- Authentication testing ------ ??? MOVEME?
340 function linkAuth($trid, $trkey)
342 $tr = DB_DataObject::factory('Documents_Tracking');
343 if (!$tr->get($trid)) {
344 return "Invalid URL";
346 if (strtolower($tr->authkey) != strtolower($trkey)) {
347 $this->AddEvent("ERROR-L", false, "Invalid Key");
348 return "Invalid KEY";
351 $this->onloadTrack = (int) $tr->doc_id;
352 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
353 $this->AddEvent("ERROR-L", false, "Key Expired");
354 return "Key Expired";
356 // user logged in and not
357 $au = $this->getAuthUser();
358 if ($au && $au->id && $au->id != $tr->person_id) {
361 return "Logged Out existing Session\n - reload to log in with correct key";
363 if ($au) { // logged in anyway..
364 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
365 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
370 // authenticate the user...
372 $u = DB_DataObject::factory('Person');
374 $u->get($tr->person_id);
376 $this->AddEvent("LOGIN", false, "With Key");
378 // we need to redirect out - otherwise refererer url will include key!
379 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
391 * ------------- Authentication password reset ------ ??? MOVEME?
397 function resetPassword($id,$t, $key)
400 $au = $this->getAuthUser();
402 return "Already Logged in - no need to use Password Reset";
405 $u = DB_DataObject::factory('Person');
406 //$u->company_id = $this->company->id;
408 if (!$u->get($id) || !strlen($u->passwd)) {
413 if ($key != $u->genPassKey($t)) {
414 return "invalid key";
417 $u->no_reset_sent = 0;
420 if ($t < strtotime("NOW - 1 DAY")) {
423 $this->showNewPass = implode("/", array($id,$t,$key));
428 * jerrAuth: standard auth failure - with data that let's the UI know..
432 $this->jerr("Not authenticated", array('authFailure' => true));
438 * ---------------- Standard JSON outputers. - used everywhere
441 function jerr($str, $errors=array()) // standard error reporting..
444 $cli = HTML_FlexyFramework::get()->cli;
446 echo "ERROR:\n" .$str . "\n";
450 require_once 'Services/JSON.php';
451 $json = new Services_JSON();
454 $this->addEvent("ERROR", false, $str);
456 if (!empty($_REQUEST['returnHTML']) ||
457 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
459 header('Content-type: text/html');
460 echo "<HTML><HEAD></HEAD><BODY>";
461 echo $json->encodeUnsafe(array(
464 'message' => $str, // compate with exeption / loadexception.
466 'errors' => $errors ? $errors : true, // used by forms to flag errors.
467 'authFailure' => !empty($errors['authFailure']),
469 echo "</BODY></HTML>";
473 echo $json->encode(array(
477 'message' => $str, // compate with exeption / loadexception.
478 'errors' => $errors ? $errors : true, // used by forms to flag errors.
479 'authFailure' => !empty($errors['authFailure']),
487 require_once 'Services/JSON.php';
488 $json = new Services_JSON();
490 if (!empty($_REQUEST['returnHTML']) ||
491 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
494 header('Content-type: text/html');
495 echo "<HTML><HEAD></HEAD><BODY>";
496 // encode html characters so they can be read..
497 echo str_replace(array('<','>'), array('\u003c','\u003e'),
498 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
499 echo "</BODY></HTML>";
504 echo $json->encode(array('success'=> true, 'data' => $str));
509 * output data for grids or tree
510 * @ar {Array} ar Array of data
511 * @total {Number|false} total number of records (or false to return count(ar)
512 * @extra {Array} extra key value list of data to pass as extra data.
515 function jdata($ar,$total=false, $extra=array())
517 // should do mobile checking???
518 if ($total == false) {
521 $extra= $extra ? $extra : array();
522 require_once 'Services/JSON.php';
523 $json = new Services_JSON();
524 if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
526 header('Content-type: text/html');
527 echo "<HTML><HEAD></HEAD><BODY>";
528 // encode html characters so they can be read..
529 echo str_replace(array('<','>'), array('\u003c','\u003e'),
530 $json->encodeUnsafe(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra));
531 echo "</BODY></HTML>";
541 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
551 * ---------------- OUTPUT
553 function hasBg($fn) // used on front page to check if logos exist..
555 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
558 * outputJavascriptIncludes:
560 * output <script....> for all the modules in the applcaiton
563 function outputJavascriptIncludes() // includes on devel version..
566 $mods = $this->modulesList();
568 foreach($mods as $mod) {
569 // add the css file..
572 $files = $this->moduleJavascriptList($mod.'/widgets');
573 foreach($files as $f) {
574 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
577 $files = $this->moduleJavascriptList($mod);
578 foreach($files as $f) {
579 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
588 * output <link rel=stylesheet......> for all the modules in the applcaiton
591 function outputCSSIncludes() // includes on CSS links.
594 $mods = $this->modulesList();
597 foreach($mods as $mod) {
598 // add the css file..
599 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
600 if (file_exists( $css)){
601 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
602 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
611 * Gather infor for javascript files..
613 * @param {String} $mod the module to get info about.
614 * @return {StdClass} details about module.
616 function moduleJavascriptFilesInfo($mod)
618 $ff = HTML_FlexyFramework::get();
620 $base = dirname($_SERVER['SCRIPT_FILENAME']);
621 $dir = $this->rootDir.'/Pman/'. $mod;
622 $path = $this->rootURL ."/Pman/$mod/";
624 $ar = glob($dir . '/*.js');
630 foreach($ar as $fn) {
632 // got the 'module file..'
633 $mtime = filemtime($dir . '/'. $f);
634 $maxtime = max($mtime, $maxtime);
635 $arfiles[$fn] = $mtime;
636 $files[] = $path . $f . '?ts='.$mtime;
639 ksort($arfiles); // just sort by name so it's consistant for serialize..
641 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
642 $basedir = $ff->Pman['public_cache_dir'];
643 $baseurl = $ff->Pman['public_cache_url'];
645 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
646 usort($files, $lsort);
648 $smod = str_replace('/','.',$mod);
650 $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
652 $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
653 ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
655 return (object) array(
658 'filesmtime' => $arfiles,
659 'maxtime' => $maxtime,
660 'compile' => $compile,
661 'translation_file' => $base .'/_translations_/' . $smod . '.js',
662 'translation_mtime' => $tmtime,
664 'translation_data' => preg_replace('/\.js$/', '.__translation__.js', $output),
665 'translation_base' => dirname($dir) . '/',
666 'basedir' => $basedir,
667 'baseurl' => $baseurl,
675 * moduleJavascriptList: list the javascript files in a module
677 * The original version of this.. still needs more thought...
679 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
680 * Translations are in Pman/_translations_/{$mod}.js
682 * if that stuff does not exist just list files in Pman/{$mod}/*.js
684 * Compiled could be done on the fly..
688 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
689 * @return {Array} list of include paths (either compiled or raw)
695 function moduleJavascriptList($mod)
699 $dir = $this->rootDir.'/Pman/'. $mod;
702 if (!file_exists($dir)) {
703 echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
707 $info = $this->moduleJavascriptFilesInfo($mod);
711 if (empty($info->files)) {
714 // finally sort the files, so they are in the right order..
716 // only compile this stuff if public_cache is set..
720 // public_cache_dir = /var/www/myproject_cache
721 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
724 // where are we going to write all of this..
725 // This has to be done via a
726 if ( $info->compile && !file_exists($info->basedir.'/'.$info->output)) {
727 require_once 'Pman/Core/JsCompile.php';
728 $x = new Pman_Core_JsCompile();
730 $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
733 if ($info->compile && file_exists($info->basedir.'/'.$info->output) && filesize($info->basedir.'/'.$info->output)) {
735 $info->baseurl.'/'. $info->output,
738 if ($info->translation_mtime) {
739 $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
746 // give up and output original files...
757 * ---------------- Logging ---------------
762 * Log an action (only if it has not been logged already.
764 * @param {String} action - group/name of event
765 * @param {DataObject|false} obj - dataobject action occured on.
766 * @param {String} any remarks
769 function addEventOnce($act, $obj = false, $remarks = '')
771 $au = $this->getAuthUser();
772 $e = DB_DataObject::factory('Events');
773 $e->init($act,$obj,$remarks);
774 if ($e->find(true)) {
777 return $this->addEvent($act, $obj, $remarks);
783 * @param {String} action - group/name of event
784 * @param {DataObject|false} obj - dataobject action occured on.
785 * @param {String} any remarks
786 * @return {Number} Event id.,
789 function addEvent($act, $obj = false, $remarks = '')
791 $au = $this->getAuthUser();
792 $e = DB_DataObject::factory('Events');
793 $e->init($act,$obj,$remarks);
795 $e->event_when = date('Y-m-d H:i:s');
798 $ff = HTML_FlexyFramework::get();
799 if (empty($ff->Pman['event_log_dir'])) {
802 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
803 if (!file_exists(dirname($file))) {
804 mkdir(dirname($file),0700,true);
806 file_put_contents($file, var_export(array(
807 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
808 'GET' => empty($_GET) ? array() : $_GET,
809 'POST' => empty($_POST) ? array() : $_POST,
815 // ------------------ DEPERCIATED ---
817 function modules() // DEPRECITAED
819 return $this->modulesList();
821 function staticGetAuthUser() // DEPRECIATED..
825 return $x->getAuthUser();