3 * Table Definition for Images
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Images extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Images'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $filename; // string(255) not_null
15 public $ontable; // string(32) not_null multiple_key
16 public $onid; // int(11) not_null
17 public $mimetype; // string(64) not_null
18 public $width; // int(11) not_null
19 public $height; // int(11) not_null
20 public $filesize; // int(11) not_null
21 public $displayorder; // int(11) not_null
22 public $language; // string(6) not_null
23 public $parent_image_id; // int(11) not_null
24 public $created; // datetime(19) not_null binary
25 public $imgtype; // string(32) not_null
26 public $linkurl; // string(254) not_null
27 public $descript; // blob(65535) not_null blob
28 public $title; // string(128) not_null
30 /* the code above is auto generated do not remove the tag below */
33 function checkPerm($lvl, $au)
35 // default permissons are to
36 // allow create / edit / if the user has
44 if (method_exists($o, 'checkPerm')) {
45 // edit permissions on related object needed...
46 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
50 return true; //// ??? not really that safe...
54 function beforeInsert($q, $roo)
56 if (isset($q['_remote_upload'])) {
57 require_once 'System.php';
59 $tmpdir = System::mktemp("-d remote_upload");
61 $path = $tmpdir . '/' . basename($q['_remote_upload']);
63 if(!file_exists($path)){
64 file_put_contents($path, file_get_contents($q['_remote_upload']));
67 $imageInfo = getimagesize($path);
69 require_once 'File/MimeType.php';
70 $y = new File_MimeType();
71 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
73 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
74 rename($path,$path.".".$ext);
78 if (!$this->createFrom($path)) {
79 $roo->jerr("erro making image" . $q['_remote_upload']);
82 if(!empty($q['_return_after_create'])){
86 $roo->addEvent("ADD", $this, $this->toEventString());
88 $r = DB_DataObject::factory($this->tableName());
93 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
100 * create an email from file.
101 * these must have been set first.
105 function createFrom($file, $filename=false)
107 // copy the file into the storage area..
108 if (!file_exists($file) || !filesize($file)) {
109 $this->err = "File $file did not exist or is 0 size";
113 $filename = empty($filename) ? $file : $filename;
115 if (empty($this->mimetype)) {
116 require_once 'File/MimeType.php';
117 $y = new File_MimeType();
118 $this->mimetype = $y->fromFilename($filename);
121 $this->mimetype= strtolower($this->mimetype);
123 if (array_shift(explode('/', $this->mimetype)) == 'image') {
125 $imgs = @getimagesize($file);
127 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
130 list($this->width , $this->height) = $imgs;
134 $this->getNumberOfPages($file);
136 $this->filesize = filesize($file);
137 $this->created = date('Y-m-d H:i:s');
140 if (empty($this->filename)) {
141 $this->filename = basename($filename);
144 //DB_DataObject::debugLevel(1);
153 $f = $this->getStoreName();
155 if (!file_exists($dest)) {
156 // currently this is 0775 due to problems using shared hosing (FTP)
157 // it makes all the files unaccessable..
158 // you can normally solve this by giving the storedirectory better perms
159 // if needed on a dedicated server..
160 $oldumask = umask(0);
161 mkdir($dest, 0775, true);
172 // $this->createThumbnail(0,50);
178 * Calculate target file name
180 * @return - target file name
182 function getStoreName()
184 $opts = HTML_FlexyFramework::get()->Pman;
185 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
186 return implode( '/', array(
187 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
193 * deletes all the image instances of it...
197 function beforeDelete()
199 $fn = $this->getStoreName();
200 if (file_exists($fn)) {
206 if (file_exists($d)) {
209 while (false !== ($fn = readdir($dh))) {
210 if (substr($fn, 0, strlen($b)) == $b) {
211 unlink($d. '/'. $fn);
218 * check mimetype against type
219 * - eg. img.is(#image#)
224 if (empty($this->mimetype)) {
227 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
231 * onUpload (singlely attached image to a table)
234 function onUploadWithTbl($tbl, $fld)
236 if ( $tbl->__table == 'Images') {
237 return; // not upload to self...
239 if (empty($_FILES['imageUpload']['tmp_name']) ||
240 empty($_FILES['imageUpload']['name']) ||
241 empty($_FILES['imageUpload']['type'])
246 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
248 $image = DB_DataObject::factory('Images');
249 $image->get($tbl->$fld);
250 $image->beforeDelete();
254 $image = DB_DataObject::factory('Images');
255 $image->onid = $tbl->id;
256 $image->ontable = $tbl->__table;
257 $image->filename = $_FILES['imageUpload']['name'];
258 $image->mimetype = $_FILES['imageUpload']['type'];
260 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
264 $tbl->$fld = $image->id;
271 function onUpload($roo)
273 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
274 if (empty($_FILES['imageUpload']['tmp_name']) ||
275 empty($_FILES['imageUpload']['name']) ||
276 empty($_FILES['imageUpload']['type'])
280 0=>"There is no error, the file uploaded with success",
281 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
282 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
283 3=>"The uploaded file was only partially uploaded",
284 4=>"No file was uploaded",
285 6=>"Missing a temporary folder"
287 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
288 $this->err = "Missing file details : Error=". $estr;
293 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
295 $this->beforeDelete();
297 if ( empty($this->ontable)) {
298 $this->err = "Missing ontable";
302 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
303 // then its an upload
304 $img = DB_DataObject::factory('Images');
305 $img->onid = $this->onid;
306 $img->ontable = $this->ontable;
307 $img->imgtype = $this->imgtype;
310 while ($img->fetch()) {
311 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
313 $img->beforeDelete();
321 require_once 'File/MimeType.php';
322 $y = new File_MimeType();
323 $this->mimetype = $_FILES['imageUpload']['type'];
324 if (in_array($this->mimetype, array(
326 'application/octet-stream',
327 'image/x-png', // WTF does this?
328 'image/pjpeg', // WTF does this?
329 'application/x-apple-msg-attachment', /// apple doing it's magic...
330 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
331 'application/csv-tab-delimited-table', // windows again!!?
332 ))) { // weird tyeps..
333 $inf = pathinfo($_FILES['imageUpload']['name']);
334 $this->mimetype = $y->fromExt($inf['extension']);
338 $ext = $y->toExt(trim((string) $this->mimetype ));
340 $this->filename = empty($this->filename) ?
341 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
345 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
346 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
356 * return a list of images for an object, optionally with a mime regex.
357 * eg. '%/pdf' or 'image/%'
361 * $i = DB_DataObject::factory('Images');
362 * $i->imgtype = 'LOGO';
363 * $ar = $i->gather($somedataobject, 'image/%');
365 * @param {DB_DataObject} dataobject = the object to gather data on.
366 * @param {String} mimelike LIKE query to use for search
369 function gather($obj, $mime_like='', $opts=array())
371 //DB_DataObject::debugLevel(1);
372 if (empty($obj->id)) {
377 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
380 if (!empty($mime_like)) {
381 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
383 $c->orderBy('created DESC');
385 return $c->fetchAll();
390 * set or get the dataobject this image is associated with
391 * @param DB_DataObject $obj An object to associate this image with
392 * (does not store it - you need to call update() to do that)
393 * @return DB_DataObject the dataobject this image is attached to.
395 function object($obj=false)
397 if ($obj === false) {
398 if (empty($this->ontable) || empty($this->onid)) {
401 $ret = DB_DataObject::factory($this->ontable);
402 $ret->get($this->onid);
407 $this->ontable = $obj->tableName();
408 $this->onid = $obj->id; /// assumes our nice standard of using ids..
413 function toRooArray($req) {
415 $ret= $this->toArray();
419 $ff = HTML_FlexyFramework::get();
422 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
423 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
425 if (!empty($req['query']['imagesize'])) {
426 // query/imageBaseURL ... depricated...? -- set it in config?
428 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
430 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
432 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
434 if (!empty($req['query']['imagesize'])) {
435 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
445 * URL - create a url for the image.
446 * size - use -1 to show full size.
447 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
451 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
454 return 'about:blank';
458 $ff = HTML_FlexyFramework::get();
459 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
460 if (preg_match('#^http[s]*://#', $provider)) {
465 $provider = preg_replace('#/Thumb$#', '', $provider);
467 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
470 //$size = max(100, (int) $size);
471 //$size = min(1024, (int) $size);
472 // the size should 200x150 to convert
473 $sizear = preg_split('/(x|c)/', $size);
474 if(empty($sizear[1])){
477 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
479 $fc = $this->toFileConvert();
482 $mt = $this->mimetype;
483 if (!preg_match('#^image/#i',$mt)) {
487 $fc->convert($mt, $size);
489 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
492 * size could be 123x345
496 function toHTML($size, $provider = '/Images/Thumb')
501 $sz = explode('x', $size);
504 if (!$this->id || empty($this->width)) {
506 $this->width = empty($sz[1]) ? $sx : $sz[1];
510 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
517 if (strlen($this->title)) {
518 $extra = ' title="'. htmlspecialchars($this->title) . '"';
521 return '<img src="' . $this->URL($size, $provider) . '"' .
523 ' width="'. $sx . '"' .
524 ' height="'. $sy . '">';
531 * #2142 [new] CMS - image link urls
536 function toLinkHTML($size, $provider = '/Images/Thumb')
538 if(empty($this->linkurl)){
539 return $this->toHTML($size, $provider = '/Images/Thumb');
542 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
548 * to Fileconvert object..
553 function toFileConvert()
555 require_once 'File/Convert.php';
556 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
563 require_once 'File/MimeType.php';
565 $y = new File_MimeType();
566 return $y->toExt($this->mimetype);
578 function setFromRoo($ar, $roo)
580 // not sure why we do this..
582 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
583 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
586 if ($this->find(true)) {
587 $roo->old = clone($this);
592 if (!empty($ar['_copy_from'])) {
594 if (!$this->checkPerm( 'A' , $roo->authUser)) {
595 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
598 $copy = DB_DataObject::factory('Images');
599 $copy->get($ar['_copy_from']);
600 $this->setFrom($copy->toArray());
602 $this->createFrom($copy->getStoreName());
604 $roo->addEvent("ADD", $this, $this->toEventString());
606 $r = DB_DataObject::factory($this->tableName());
611 $roo->jok($r->toArray());
618 // FIXME - we should be checking perms here...
620 // this should be doign update
623 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
624 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
629 if (!isset($_FILES['imageUpload'])) {
630 return; // standard update...
634 // print_r(!$this->onUpload($this));
636 if ( !$this->onUpload($this)) {
637 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
640 $this->addEvent($ar, $roo);
642 $r = DB_DataObject::factory($this->tableName());
647 $roo->jok($r->toArray());
651 function addEvent($ar, $roo)
653 $roo->addEvent("ADD", $this, $this->toEventString());
656 function toEventString()
659 //$p = DB_DataObject::factory($this->ontable);
661 // return "ERROR unknown table? {$this->ontable}";
665 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
666 //$p->toEventString();
669 function onUploadFromData($data, $roo)
672 $this->err = "Missing file details";
677 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
679 $this->beforeDelete();
682 if (empty($this->ontable)) {
683 $this->err = "Missing ontable";
687 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
688 // then its an upload
689 $img = DB_DataObject::factory('Images');
690 $img->onid = $this->onid;
691 $img->ontable = $this->ontable;
692 $img->imgtype = $this->imgtype;
695 while ($img->fetch()) {
696 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
698 $img->beforeDelete();
704 require_once 'File/MimeType.php';
705 $y = new File_MimeType();
707 if (in_array($this->mimetype, array(
709 'application/octet-stream',
710 'image/x-png', // WTF does this?
711 'image/pjpeg', // WTF does this?
712 'application/x-apple-msg-attachment', /// apple doing it's magic...
713 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
714 'application/csv-tab-delimited-table', // windows again!!?
715 ))) { // weird tyeps..
716 $inf = pathinfo($this->filename);
717 $this->mimetype = $y->fromExt($inf['extension']);
720 $ext = $y->toExt(trim((string) $this->mimetype ));
722 if(array_pop(explode('.', $this->filename)) != $ext){
723 $this->filename = $this->filename .'.'. $ext;
726 if (!$this->createFromData($data)) {
734 function createFromData($data)
737 $this->mimetype= strtolower($this->mimetype);
739 if (array_shift(explode('/', $this->mimetype)) == 'image') {
741 $imgs = @getimagesize($data);
743 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
744 list($this->width , $this->height) = $imgs;
748 $this->created = date('Y-m-d H:i:s');
756 $f = $this->getStoreName();
758 if (!file_exists($dest)) {
759 $oldumask = umask(0);
760 mkdir($dest, 0775, true);
764 file_put_contents($f, file_get_contents("data://" . $data));
768 $this->filesize = filesize($f);
778 if(!preg_match('/^image\//', $this->mimetype)){
782 $file = $this->getStoreName();
784 if(!file_exists($file)){
788 $data = file_get_contents($file);
790 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
795 function getNumberOfPages($file)
797 require_once 'System.php';
799 $this->no_of_pages = 0;
801 if(!file_exists($file)){
806 * We handle pdf only at present
808 switch ($this->mimetype) {
810 case 'application/pdf' :
812 $pdfinfo = System::which('pdfinfo');
814 if (empty($pdfinfo)) {
818 $cmd = "{$pdfinfo} {$file}";
822 $infos = explode("\n", $info);
824 foreach ($infos as $i){
826 if(!preg_match('/^NumberOfPages: ([0-9]+)/', $i, $matches)){
830 $ret = (empty($matches[1])) ? false : $matches[1];