DataObjects/Core_company.php
[Pman.Core] / DataObjects / Core_company.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_Company extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_company';                       // table name
13     public $code;                            // string(32)  not_null
14     public $name;                            // string(128)  
15     public $remarks;                         // blob(65535)  blob
16     public $owner_id;                        // int(11)  not_null
17     public $address;                         // blob(65535)  blob
18     public $tel;                             // string(32)  
19     public $fax;                             // string(32)  
20     public $email;                           // string(128)  
21     public $id;                              // int(11)  not_null primary_key auto_increment
22     public $isOwner;                         // int(11)  
23     public $logo_id;                         // int(11)  not_null
24     public $background_color;                // string(8)  not_null
25     public $comptype;                        // string(8)  not_null
26     public $url;                             // string(254)  not_null
27     public $main_office_id;                  // int(11)  not_null
28     public $created_by;                      // int(11)  not_null
29     public $created_dt;                      // datetime(19)  not_null binary
30     public $updated_by;                      // int(11)  not_null
31     public $updated_dt;                      // datetime(19)  not_null binary
32     public $passwd;                          // string(64)  not_null
33     public $dispatch_port;                   // string(255)  not_null
34     public $province;                        // string(255)  not_null
35     public $country;                         // string(4)  not_null
36     public $is_system;                       // int(2)
37     
38     /* the code above is auto generated do not remove the tag below */
39     ###END_AUTOCODE
40     
41     function applyFilters($q, $au)
42     {
43         
44         $tn = $this->tableName();
45         $this->selectAdd("i18n_translate('c' , {$tn}.country, 'en') as country_display_name ");
46       
47         $tn = $this->tableName();
48         //DB_DataObject::debugLevel(1);
49         $x = DB_DataObject::factory('core_company');
50         $x->comptype= 'OWNER';
51         $x->find(true);
52
53         if (!empty($q['query']['company_project_id'])) {
54             $add = '';
55             if (!empty($q['query']['company_include_self'])) {
56                 $add = " OR {$tn}.id = {$x->id}";
57             }
58             if (!empty($q['query']['company_not_self'])) {
59                 $add = " AND {$tn}.id != {$x->id}";
60             }
61             
62             $pids = array();
63             $pid = $q['query']['company_project_id'];
64             if (strpos($pid, ',')) {
65                 $bits = explode(',', $pid);
66                 foreach($bits as $b) {
67                     $pids[] = (int)$b;
68                 }
69             } else {
70                 $pids = array($pid);
71             }
72             
73             
74             $pids = implode(',', $pids);
75             $this->whereAdd("{$tn}.id IN (
76                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
77             ) $add" );
78              
79         }
80         if (!empty($q['query']['comptype'])) {
81            
82             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
83             
84         }
85         
86         // depricated - should be moved to module specific (texon afair)
87         
88          if (!empty($q['query']['province'])) {
89              $prov = $this->escape($q['query']['province']);
90             $this->whereAdd("province LIKE '$prov%'");
91             
92             
93         }
94         // ADD comptype_display name.. = for combos..
95         $this->selectAdd("
96             (SELECT display_name
97                 FROM
98                     core_enum
99                 WHERE
100                     etype='comptype'
101                     AND
102                     name={$tn}.comptype
103                 LIMIT 1
104                 ) as comptype_display_name
105         ");
106         
107         if(!empty($q['query']['name'])){
108             $s = $this->escape($q['query']['name']);
109             $this->whereAdd("
110                 {$tn}.name LIKE '%$s%'
111             ");
112         }
113         if(!empty($q['search']['name'])){ 
114             $s = $this->escape($q['search']['name']);
115             $this->whereAdd("
116                 {$tn}.name LIKE '%$s%'
117             ");
118         }
119         if(!empty($q['search']['name_starts'])){
120             $s = $this->escape($q['search']['name_starts']);
121             $this->whereAdd("
122                 {$tn}.name LIKE '$s%'
123             ");
124         }
125     }
126     
127     function toEventString() {
128         return $this->name;
129     }
130     
131     // ---------- AUTHENTICATION
132     // not sure where authetnication via company is used?? posibly media-outreach
133     
134     function isAuth()
135     {
136         $db = $this->getDatabaseConnection();
137         $sesPrefix = $db->dsn['database'];
138         @session_start();
139         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
140             // in session...
141             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
142             $u = DB_DataObject::factory('core_company');
143             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
144                 return true;
145             }
146             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
147             
148         }
149         // not in session or not matched...
150         
151         
152         return false;
153         
154     }
155     function getAuthUser()
156     {
157         if (!$this->isAuth()) {
158             return false;
159         }
160         $db = $this->getDatabaseConnection();
161         $sesPrefix = $db->dsn['database'];
162         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
163             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
164             
165             $u = DB_DataObject::factory('core_company');
166             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
167                 return clone($u);
168             }
169              
170         }
171         
172         
173         return false;
174     }     
175     function login()
176     {
177         $this->isAuth(); // force session start..
178          $db = $this->getDatabaseConnection();
179         $sesPrefix = $db->dsn['database'];
180         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
181         
182     }
183     function logout()
184     {
185         $this->isAuth(); // force session start..
186         $db = $this->getDatabaseConnection();
187         $sesPrefix = $db->dsn['database'];
188         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
189         
190     }    
191     // ---------- AUTHENTICATION
192     function checkPassword($val)
193     {
194         //echo '<pre>'.$val .  print_R($this,true);
195         if (substr($this->passwd,0,1) == '$') {
196             return crypt($val,$this->passwd) == $this->passwd ;
197         }
198         // old style md5 passwords...- cant be used with courier....
199         return md5($val) == $this->passwd;
200     }
201     function setPassword($value) 
202     {
203         $salt='';
204         while(strlen($salt)<9) {
205             $salt.=chr(rand(64,126));
206             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
207         }
208         $this->passwd = crypt($value, '$1$'. $salt. '$');
209        
210     }      
211     function onUpload($controller)
212     {
213         $image = DB_DataObject::factory('Images');
214         return $image->onUploadWithTbl($this, 'logo_id');
215          
216     }
217     function  onUpdate($old, $req,$roo) 
218     {
219         if (!empty($req['password1'])) {
220             $this->setPassword($req['password1']);
221             $this->update();
222         }
223     }
224     function onInsert($req, $roo)
225     {
226         if (!empty($this->logo_id)) { // update images table to sycn with this..
227             $img = DB_DataObject::factory('Images');
228             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
229                 $img->onid = $this->id;
230                 $img->update();
231             }
232         }
233         if (!empty($req['password1'])) {
234             $this->setPassword($req['password1']);
235             $this->update();
236         }
237         $img = DB_DataObject::factory('Images');
238         $img->onid= 0;
239         
240         $img->ontable = $this->tableName();
241         $img->imgtype = 'LOGO';
242         // should check uploader!!!
243         if ($img->find()) {
244             while($img->fetch()) {
245                 $ii = clone($img);
246                 $ii->onid = $this->id;
247                 $ii->update();
248                 $this->logo_id = $ii->id;
249             }
250             $this->update();
251         }
252         
253     }
254     
255     function beforeInsert($q, $roo)
256     {
257         // we still use comptype in some old systems...
258         
259         if (!empty($q['comptype_id'])) {
260             $en = DB_DataObject::Factory('core_enum');
261             $en->get($q['comptype_id']);
262             $this->comptype = $en->name;
263         }
264         
265         if(!empty($q['_check_name'])){
266             if($this->checkName()){
267                 $roo->jok('OK');
268             }
269             
270             $roo->jerr('EXIST');
271         }
272     }
273     
274     function beforeUpdate($old, $q,$roo)
275     {
276         // we still use comptype in some old systems...
277         
278         if (!empty($q['comptype_id'])) {
279             $en = DB_DataObject::Factory('core_enum');
280             $en->get($q['comptype_id']);
281             $this->comptype = $en->name;
282         }
283         
284         
285         if(!empty($q['_flag_delete'])){
286             $this->deleted_dt = $this->sqlValue("NOW()");
287             $this->deleted_by = $roo->getAuthUser()->id;
288         }
289         
290         if(!empty($q['_flag_undelete'])){
291             $this->deleted_dt = "";
292             $this->deleted_by = 0;
293         }
294         if(!empty($q['_check_name'])){
295             if($this->checkName()){
296                 $roo->jok('OK');
297             }
298             
299             $roo->jerr('EXIST');
300         }
301         
302         if(!empty($q['_merge_id'])){
303             $this->merge($q['_merge_id'], $roo);
304         }
305         
306         if(!empty($this->is_system) && 
307             ($old->code != $this->code  ) // used to be not allowed to change name..
308         ){
309             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
310         }
311     }
312     
313     function beforeDelete($req, $roo)
314     {
315         
316         // should check for members....
317         if(!empty($this->is_system) && 
318             ($old->code != $this->code || $old->name != $this->name)
319         ){
320             $roo->jerr('This company is not allow to delete');
321         }
322         
323         
324     }
325     function onDelete($req, $roo)
326     {   
327         $img = DB_DataObject::factory('Images');
328         $img->ontable = $this->tableName();
329         $img->onid = $this->id;
330         $img->find();
331         while ($img->fetch()) {
332             $img->beforeDelete();
333             $img->delete();
334         }
335         return true;
336         
337          
338     }
339     /**
340      * check who is trying to access this. false == access denied..
341      */
342     function checkPerm($lvl, $au, $changes = false) 
343     {
344         
345         // do we have an empty system..
346         if ($au && $au->id == -1) {
347             return true;
348         }
349         
350         
351         
352         if ($au->company()->comptype != 'OWNER') {
353             
354             // hacking!
355             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
356                 return false;
357             }
358             
359             return $this->id == $au->company_id;
360         }
361         
362         return $au->hasPerm("Core.Companies", $lvl);    
363     }
364     
365     function logoImageToHTML($size)
366     {
367         $i = DB_DataObject::factory('Images');
368         if (!$this->logo_id || !$i->get($this->logo_id)) {
369             return '';
370         }
371         return $i->toHTML($size);
372         
373     }
374      function firstImage($filter='image/%')
375     {
376         $i = DB_DataObject::factory('Images');
377         //DB_DataObject::debugLevel(1);
378         $im = $i->gather($this, $filter);
379         if (empty($im)) {
380             return false;
381         }
382         return $im[0];
383     }
384     
385     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
386     {
387         $fm = $this->firstImage($filter);
388          if (empty($fm)) {
389             return '';
390         }
391         return $fm->toHTML($size, $base);
392     }
393     
394     function toRooSingleArray($authUser, $request)
395     {
396         $ret = $this->toArray();
397        // DB_DataObject::debugLevel(1);
398         // get the comptype display
399         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
400         
401         $ret['comptype_display'] = $ret['comptype'];
402         if ($e   && !empty($e->name_display)) {
403             $ret['comptype_display'] = $e->name_display;
404         }
405         
406         
407         return $ret;
408     }
409     
410     /**
411      * # 2028 
412      * create the suppliers...
413      * 
414      * @param object $roo
415      * @param array $data
416      * 
417      */
418     function initCompaniesArray($roo, $data)
419     {
420         $tn = $this->tableName();
421         
422         foreach($data as $d){
423             $com = DB_DataObject::factory($tn);
424             $com->setFrom($d);
425             if(!$com->find(true)){
426                 $com->created_dt = Date('Y-m-d H:i:s');
427                 $com->updated_dt = Date('Y-m-d H:i:s');
428                 $com->is_system = 1;// new column.. block the user changing the code and name..
429                 $com->insert();
430             }
431         }
432         
433         
434     }
435     
436     
437     function initCompanies($roo, $opts)
438     {
439         $companies = DB_DataObject::factory('core_company');
440         
441         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
442         
443         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
444         
445         if (empty($enum)) {
446             $roo->jerr("invalid company type '$ctype'");
447         }
448         if ($ctype =='OWNER') {
449             $companies = DB_DataObject::factory('core_company');
450             $companies->comptype_id = $enum;
451             if ($companies->count()) {
452                 $roo->jerr("Owner  company already exists");
453             }
454         }
455         $companies = DB_DataObject::factory('core_company');
456         
457         // check that 
458         $companies->setFrom(array(
459             'name' => $opts['add-company'],
460             'comptype' => $ctype,
461             'comptype_id' => $enum,
462         ));
463         if ($companies->find(true)) {
464             $roo->jerr("company already exists");
465         }
466         $companies->setFrom(array(
467             'background_color' => '',
468             'created_dt' => $this->sqlValue('NOW()'),
469             'updated_dt' => $this->sqlValue('NOW()')
470         ));
471         
472         
473         $companies->insert();
474         $companies->onInsert(array(), $roo);
475     }
476     static function lookupOwner()
477     {
478         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
479         $companies = DB_DataObject::factory('core_company');
480         $companies->comptype_id = $enum;
481         if ($companies->find(true)) {
482             return $companies;
483         }
484         return false;
485     }
486     
487     function merge($merge_to, $roo)
488     {
489         $affects  = array();
490         
491         $all_links = $this->databaseLinks();
492         
493         foreach($all_links as $tbl => $links) {
494             foreach($links as $col => $totbl_col) {
495                 $to = explode(':', $totbl_col);
496                 if ($to[0] != $this->tableName()) {
497                     continue;
498                 }
499                 
500                 $affects[$tbl .'.' . $col] = true;
501             }
502         }
503         
504         foreach($affects as $k => $true) {
505             $ka = explode('.', $k);
506
507             $chk = DB_DataObject::factory($ka[0]);
508             
509             if (!is_a($chk,'DB_DataObject')) {
510                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
511             }
512             
513             $chk->{$ka[1]} = $this->id;
514
515             foreach ($chk->fetchAll() as $c){
516                 $cc = clone ($c);
517                 $c->{$ka[1]} = $merge_to;
518                 $c->update($cc);
519             }
520         }
521         
522         $this->delete();
523         
524         $roo->jok('Merged');
525         
526     }
527     
528     function checkName()
529     {
530         $company = DB_DataObject::factory('core_company');
531         $company->setFrom(array(
532             'name' => $this->name
533         ));
534         
535         if(!empty($this->id)){
536             $company->whereAdd("id != {$this->id}");
537         }
538         
539         if(!$company->find(true)){
540             return true;
541         }
542         
543         return false;
544     }
545 }