DataObjects/Core_watch.php
[Pman.Core] / DataObjects / Companies.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Companies extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Companies';                       // 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         $tn = $this->tableName();
44         //DB_DataObject::debugLevel(1);
45         $x = DB_DataObject::factory('Companies');
46         $x->comptype= 'OWNER';
47         $x->find(true);
48         
49         if (!empty($q['query']['company_project_id'])) {
50             $add = '';
51             if (!empty($q['query']['company_include_self'])) {
52                 $add = ' OR Companies.id = ' . $x->id;
53             }
54             if (!empty($q['query']['company_not_self'])) {
55                 $add = ' AND Companies.id != ' . $x->id;
56             }
57             $pids = array();
58             $pid = $q['query']['company_project_id'];
59             if (strpos($pid, ',')) {
60                 $bits = explode(',', $pid);
61                 foreach($bits as $b) {
62                     $pids[] = (int)$b;
63                 }
64             } else {
65                 $pids = array($pid);
66             }
67             
68             
69             $pids = implode(',', $pids);
70             $this->whereAdd("Companies.id IN (
71                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
72             ) $add" );
73              
74         }
75         if (!empty($q['query']['comptype'])) {
76            
77             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
78             
79         }
80         
81         // depricated - should be moved to module specific (texon afair)
82         
83          if (!empty($q['query']['province'])) {
84              $prov = $this->escape($q['query']['province']);
85             $this->whereAdd("province LIKE '$prov%'");
86             
87             
88         }
89         // ADD comptype_display name.. = for combos..
90         $this->selectAdd("
91             (SELECT display_name
92                 FROM
93                     core_enum
94                 WHERE
95                     etype='comptype'
96                     AND
97                     name={$tn}.comptype
98                 LIMIT 1
99                 ) as comptype_display_name
100         ");
101         
102          
103     }
104     
105     function toEventString() {
106         return $this->name;
107     }
108     
109     // ---------- AUTHENTICATION
110      function isAuth()
111     {
112         $db = $this->getDatabaseConnection();
113         $sesPrefix = $db->dsn['database'];
114         @session_start();
115         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
116             // in session...
117             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
118             $u = DB_DataObject::factory('Companies');
119             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
120                 return true;
121             }
122             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
123             
124         }
125         // not in session or not matched...
126         
127         
128         return false;
129         
130     }
131     function getAuthUser()
132     {
133         if (!$this->isAuth()) {
134             return false;
135         }
136         $db = $this->getDatabaseConnection();
137         $sesPrefix = $db->dsn['database'];
138         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
139             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
140             
141             $u = DB_DataObject::factory('Companies');
142             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
143                 return clone($u);
144             }
145              
146         }
147         
148         
149         return false;
150     }     
151     function login()
152     {
153         $this->isAuth(); // force session start..
154          $db = $this->getDatabaseConnection();
155         $sesPrefix = $db->dsn['database'];
156         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
157         
158     }
159     function logout()
160     {
161         $this->isAuth(); // force session start..
162         $db = $this->getDatabaseConnection();
163         $sesPrefix = $db->dsn['database'];
164         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
165         
166     }    
167     // ---------- AUTHENTICATION
168     function checkPassword($val)
169     {
170         //echo '<pre>'.$val .  print_R($this,true);
171         if (substr($this->passwd,0,1) == '$') {
172             return crypt($val,$this->passwd) == $this->passwd ;
173         }
174         // old style md5 passwords...- cant be used with courier....
175         return md5($val) == $this->passwd;
176     }
177     function setPassword($value) 
178     {
179         $salt='';
180         while(strlen($salt)<9) {
181             $salt.=chr(rand(64,126));
182             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
183         }
184         $this->passwd = crypt($value, '$1$'. $salt. '$');
185        
186     }      
187     function onUpload($controller)
188     {
189         $image = DB_DataObject::factory('Images');
190         return $image->onUploadWithTbl($this, 'logo_id');
191          
192     }
193     function  onUpdate($old, $req,$roo) 
194     {
195         if (!empty($req['password1'])) {
196             $this->setPassword($req['password1']);
197             $this->update();
198         }
199     }
200     function onInsert($req, $roo)
201     {
202         if (!empty($this->logo_id)) { // update images table to sycn with this..
203             $img = DB_DataObject::factory('Images');
204             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
205                 $img->onid = $this->id;
206                 $img->update();
207             }
208         }
209         if (!empty($req['password1'])) {
210             $this->setPassword($req['password1']);
211             $this->update();
212         }
213         $img = DB_DataObject::factory('Images');
214         $img->onid= 0;
215         
216         $img->ontable = 'Companies';
217         $img->imgtype = 'LOGO';
218         // should check uploader!!!
219         if ($img->find()) {
220             while($img->fetch()) {
221                 $ii = clone($img);
222                 $ii->onid = $this->id;
223                 $ii->update();
224                 $this->logo_id = $ii->id;
225             }
226             $this->update();
227         }
228         
229         
230         
231         
232     }
233     
234     function beforeUpdate($old, $q,$roo)
235     {
236         if(!empty($this->is_system) && 
237             ($old->code != $this->code || $old->name != $this->name)
238         ){
239             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
240         }
241     }
242     
243     function beforeDelete($req, $roo)
244     {
245         // should check for members....
246         if(!empty($this->is_system) && 
247             ($old->code != $this->code || $old->name != $this->name)
248         ){
249             $roo->jerr('This company is not allow to delete');
250         }
251         $img = DB_DataObject::factory('Images');
252         $img->ontable = 'Companies';
253         $img->onid = $this->id;
254         $img->find();
255         while ($img->fetch()) {
256             $img->beforeDelete();
257             $img->delete();
258         }
259         return true;
260         
261          
262     }
263     /**
264      * check who is trying to access this. false == access denied..
265      */
266     function checkPerm($lvl, $au, $changes = false) 
267     {
268         
269         // do we have an empty system..
270         if ($au && $au->id == -1) {
271             return true;
272         }
273         
274         
275         
276         if ($au->company()->comptype != 'OWNER') {
277             
278             // hacking!
279             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
280                 return false;
281             }
282             
283             return $this->id == $au->company_id;
284         }
285         
286         return $au->hasPerm("Core.Companies", $lvl);    
287     }
288     
289     function logoImageToHTML($size)
290     {
291         $i = DB_DataObject::factory('Images');
292         if (!$this->logo_id || !$i->get($this->logo_id)) {
293             return '';
294         }
295         return $i->toHTML($size);
296         
297     }
298      function firstImage($filter='image/%')
299     {
300         $i = DB_DataObject::factory('Images');
301         //DB_DataObject::debugLevel(1);
302         $im = $i->gather($this, $filter);
303         if (empty($im)) {
304             return false;
305         }
306         return $im[0];
307     }
308     
309     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
310     {
311         $fm = $this->firstImage($filter);
312          if (empty($fm)) {
313             return '';
314         }
315         return $fm->toHTML($size, $base);
316     }
317     
318     function toRooSingleArray($authUser, $request)
319     {
320         $ret = $this->toArray();
321        // DB_DataObject::debugLevel(1);
322         // get the comptype display
323         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
324         
325         $ret['comptype_display'] = $ret['comptype'];
326         if ($e->find(true) && !empty($e->name_display)) {
327             $ret['comptype_display'] = $e->name_display;
328         }
329         
330         
331         return $ret;
332     }
333     
334     /**
335      * # 2028 
336      * create the suppliers...
337      * 
338      * @param object $roo
339      * @param array $data
340      * 
341      */
342     function initCompaniesArray($roo, $data)
343     {
344         $tn = $this->tableName();
345         
346         foreach($data as $d){
347             $com = DB_DataObject::factory($tn);
348             $com->setFrom($d);
349             if(!$com->find(true)){
350                 $com->created_dt = Date('Y-m-d H:i:s');
351                 $com->updated_dt = Date('Y-m-d H:i:s');
352                 $com->is_system = 1;// new column.. block the user changing the code and name..
353                 $com->insert();
354             }
355         }
356         
357         
358     }
359     
360     
361     function initCompanies($roo, $opts)
362     {
363         $companies = DB_DataObject::factory('companies');
364         
365         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
366         
367         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
368         
369         if (empty($enum)) {
370             $roo->jerr("invalid company type '$ctype'");
371         }
372         if ($ctype =='OWNER') {
373             $companies = DB_DataObject::factory('companies');
374             $companies->comptype_id = $enum;
375             if ($companies->count()) {
376                 $roo->jerr("Owner  company already exists");
377             }
378         }
379         $companies = DB_DataObject::factory('companies');
380         
381         // check that 
382         $companies->setFrom(array(
383             'name' => $opts['add-company'],
384             'comptype' => $ctype,
385             'comptype_id' => $enum,
386         ));
387         if ($companies->find(true)) {
388             $roo->jerr("company already exists");
389         }
390         $companies->setFrom(array(
391             'background_color' => '',
392             'created_dt' => $this->sqlValue('NOW()'),
393             'updated_dt' => $this->sqlValue('NOW()')
394         ));
395         
396         
397         $companies->insert();
398         $companies->onInsert(array(), $roo);
399     }
400     function    lookupOwner()
401     {
402         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
403         $companies = DB_DataObject::factory('companies');
404         $companies->comptype_id = $enum;
405         if ($companies->find(true)) {
406             return $companies;
407         }
408         return false;
409     }
410 }