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 if($this->mimetype == 'application/pdf'){
135 $this->no_of_pages = $this->getPdfPages($file);
138 $this->filesize = filesize($file);
139 $this->created = date('Y-m-d H:i:s');
142 if (empty($this->filename)) {
143 $this->filename = basename($filename);
146 //DB_DataObject::debugLevel(1);
155 $f = $this->getStoreName();
157 if (!file_exists($dest)) {
158 // currently this is 0775 due to problems using shared hosing (FTP)
159 // it makes all the files unaccessable..
160 // you can normally solve this by giving the storedirectory better perms
161 // if needed on a dedicated server..
162 $oldumask = umask(0);
163 mkdir($dest, 0775, true);
174 // $this->createThumbnail(0,50);
180 * Calculate target file name
182 * @return - target file name
184 function getStoreName()
186 $opts = HTML_FlexyFramework::get()->Pman;
187 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
188 print_r(implode( '/', array(
189 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
191 return implode( '/', array(
192 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
198 * deletes all the image instances of it...
202 function beforeDelete()
204 $fn = $this->getStoreName();
205 if (file_exists($fn)) {
211 if (file_exists($d)) {
214 while (false !== ($fn = readdir($dh))) {
215 if (substr($fn, 0, strlen($b)) == $b) {
216 unlink($d. '/'. $fn);
223 * check mimetype against type
224 * - eg. img.is(#image#)
229 if (empty($this->mimetype)) {
232 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
236 * onUpload (singlely attached image to a table)
239 function onUploadWithTbl($tbl, $fld)
241 if ( $tbl->__table == 'Images') {
242 return; // not upload to self...
244 if (empty($_FILES['imageUpload']['tmp_name']) ||
245 empty($_FILES['imageUpload']['name']) ||
246 empty($_FILES['imageUpload']['type'])
251 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
253 $image = DB_DataObject::factory('Images');
254 $image->get($tbl->$fld);
255 $image->beforeDelete();
259 $image = DB_DataObject::factory('Images');
260 $image->onid = $tbl->id;
261 $image->ontable = $tbl->__table;
262 $image->filename = $_FILES['imageUpload']['name'];
263 $image->mimetype = $_FILES['imageUpload']['type'];
265 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
269 $tbl->$fld = $image->id;
276 function onUpload($roo)
278 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
279 if (empty($_FILES['imageUpload']['tmp_name']) ||
280 empty($_FILES['imageUpload']['name']) ||
281 empty($_FILES['imageUpload']['type'])
285 0=>"There is no error, the file uploaded with success",
286 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
287 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
288 3=>"The uploaded file was only partially uploaded",
289 4=>"No file was uploaded",
290 6=>"Missing a temporary folder"
292 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
293 $this->err = "Missing file details : Error=". $estr;
298 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
300 $this->beforeDelete();
302 if ( empty($this->ontable)) {
303 $this->err = "Missing ontable";
307 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
308 // then its an upload
309 $img = DB_DataObject::factory('Images');
310 $img->onid = $this->onid;
311 $img->ontable = $this->ontable;
312 $img->imgtype = $this->imgtype;
315 while ($img->fetch()) {
316 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
318 $img->beforeDelete();
326 require_once 'File/MimeType.php';
327 $y = new File_MimeType();
328 $this->mimetype = $_FILES['imageUpload']['type'];
329 if (in_array($this->mimetype, array(
331 'application/octet-stream',
332 'image/x-png', // WTF does this?
333 'image/pjpeg', // WTF does this?
334 'application/x-apple-msg-attachment', /// apple doing it's magic...
335 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
336 'application/csv-tab-delimited-table', // windows again!!?
337 ))) { // weird tyeps..
338 $inf = pathinfo($_FILES['imageUpload']['name']);
339 $this->mimetype = $y->fromExt($inf['extension']);
343 $ext = $y->toExt(trim((string) $this->mimetype ));
345 $this->filename = empty($this->filename) ?
346 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
350 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
351 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
361 * return a list of images for an object, optionally with a mime regex.
362 * eg. '%/pdf' or 'image/%'
366 * $i = DB_DataObject::factory('Images');
367 * $i->imgtype = 'LOGO';
368 * $ar = $i->gather($somedataobject, 'image/%');
370 * @param {DB_DataObject} dataobject = the object to gather data on.
371 * @param {String} mimelike LIKE query to use for search
374 function gather($obj, $mime_like='', $opts=array())
376 //DB_DataObject::debugLevel(1);
377 if (empty($obj->id)) {
382 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
385 if (!empty($mime_like)) {
386 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
388 $c->orderBy('created DESC');
390 return $c->fetchAll();
395 * set or get the dataobject this image is associated with
396 * @param DB_DataObject $obj An object to associate this image with
397 * (does not store it - you need to call update() to do that)
398 * @return DB_DataObject the dataobject this image is attached to.
400 function object($obj=false)
402 if ($obj === false) {
403 if (empty($this->ontable) || empty($this->onid)) {
406 $ret = DB_DataObject::factory($this->ontable);
407 $ret->get($this->onid);
412 $this->ontable = $obj->tableName();
413 $this->onid = $obj->id; /// assumes our nice standard of using ids..
418 function toRooArray($req) {
420 $ret= $this->toArray();
424 $ff = HTML_FlexyFramework::get();
427 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
428 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
430 if (!empty($req['query']['imagesize'])) {
431 // query/imageBaseURL ... depricated...? -- set it in config?
433 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
435 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
437 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
439 if (!empty($req['query']['imagesize'])) {
440 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
450 * URL - create a url for the image.
451 * size - use -1 to show full size.
452 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
456 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
459 return 'about:blank';
463 $ff = HTML_FlexyFramework::get();
464 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
465 if (preg_match('#^http[s]*://#', $provider)) {
470 $provider = preg_replace('#/Thumb$#', '', $provider);
472 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
475 //$size = max(100, (int) $size);
476 //$size = min(1024, (int) $size);
477 // the size should 200x150 to convert
478 $sizear = preg_split('/(x|c)/', $size);
479 if(empty($sizear[1])){
482 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
484 $fc = $this->toFileConvert();
487 $mt = $this->mimetype;
488 if (!preg_match('#^image/#i',$mt)) {
492 $fc->convert($mt, $size);
494 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
497 * size could be 123x345
501 function toHTML($size, $provider = '/Images/Thumb')
506 $sz = explode('x', $size);
509 if (!$this->id || empty($this->width)) {
511 $this->width = empty($sz[1]) ? $sx : $sz[1];
515 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
522 if (strlen($this->title)) {
523 $extra = ' title="'. htmlspecialchars($this->title) . '"';
526 return '<img src="' . $this->URL($size, $provider) . '"' .
528 ' width="'. $sx . '"' .
529 ' height="'. $sy . '">';
536 * #2142 [new] CMS - image link urls
541 function toLinkHTML($size, $provider = '/Images/Thumb')
543 if(empty($this->linkurl)){
544 return $this->toHTML($size, $provider = '/Images/Thumb');
547 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
553 * to Fileconvert object..
558 function toFileConvert()
560 require_once 'File/Convert.php';
561 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
568 require_once 'File/MimeType.php';
570 $y = new File_MimeType();
571 return $y->toExt($this->mimetype);
583 function setFromRoo($ar, $roo)
585 // not sure why we do this..
587 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
588 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
591 if ($this->find(true)) {
592 $roo->old = clone($this);
597 if (!empty($ar['_copy_from'])) {
599 if (!$this->checkPerm( 'A' , $roo->authUser)) {
600 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
603 $copy = DB_DataObject::factory('Images');
604 $copy->get($ar['_copy_from']);
605 $this->setFrom($copy->toArray());
607 $this->createFrom($copy->getStoreName());
609 $roo->addEvent("ADD", $this, $this->toEventString());
611 $r = DB_DataObject::factory($this->tableName());
616 $roo->jok($r->toArray());
623 // FIXME - we should be checking perms here...
625 // this should be doign update
628 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
629 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
634 if (!isset($_FILES['imageUpload'])) {
635 return; // standard update...
639 // print_r(!$this->onUpload($this));
641 if ( !$this->onUpload($this)) {
642 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
645 $this->addEvent($ar, $roo);
647 $r = DB_DataObject::factory($this->tableName());
652 $roo->jok($r->toArray());
656 function addEvent($ar, $roo)
658 $roo->addEvent("ADD", $this, $this->toEventString());
661 function toEventString()
664 //$p = DB_DataObject::factory($this->ontable);
666 // return "ERROR unknown table? {$this->ontable}";
670 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
671 //$p->toEventString();
674 function onUploadFromData($data, $roo)
677 $this->err = "Missing file details";
682 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
684 $this->beforeDelete();
687 if (empty($this->ontable)) {
688 $this->err = "Missing ontable";
692 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
693 // then its an upload
694 $img = DB_DataObject::factory('Images');
695 $img->onid = $this->onid;
696 $img->ontable = $this->ontable;
697 $img->imgtype = $this->imgtype;
700 while ($img->fetch()) {
701 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
703 $img->beforeDelete();
709 require_once 'File/MimeType.php';
710 $y = new File_MimeType();
712 if (in_array($this->mimetype, array(
714 'application/octet-stream',
715 'image/x-png', // WTF does this?
716 'image/pjpeg', // WTF does this?
717 'application/x-apple-msg-attachment', /// apple doing it's magic...
718 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
719 'application/csv-tab-delimited-table', // windows again!!?
720 ))) { // weird tyeps..
721 $inf = pathinfo($this->filename);
722 $this->mimetype = $y->fromExt($inf['extension']);
725 $ext = $y->toExt(trim((string) $this->mimetype ));
727 if(array_pop(explode('.', $this->filename)) != $ext){
728 $this->filename = $this->filename .'.'. $ext;
731 if (!$this->createFromData($data)) {
739 function createFromData($data)
742 $this->mimetype= strtolower($this->mimetype);
744 if (array_shift(explode('/', $this->mimetype)) == 'image') {
746 $imgs = @getimagesize($data);
748 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
749 list($this->width , $this->height) = $imgs;
753 $this->created = date('Y-m-d H:i:s');
761 $f = $this->getStoreName();
763 if (!file_exists($dest)) {
764 $oldumask = umask(0);
765 mkdir($dest, 0775, true);
769 file_put_contents($f, file_get_contents("data://" . $data));
773 $this->filesize = filesize($f);
775 if($this->mimetype == 'application/pdf'){
776 $this->no_of_pages = $this->getPdfPages($f);
787 if(!preg_match('/^image\//', $this->mimetype)){
791 $file = $this->getStoreName();
793 if(!file_exists($file)){
797 $data = file_get_contents($file);
799 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
804 function getPdfPages($file)
806 require_once 'System.php';
810 $pdfinfo = System::which('pdfinfo');
812 if (!file_exists($file) || empty($pdfinfo)) {
816 $cmd = "{$pdfinfo} {$file}";
820 $info = explode("\n", $ret);
822 foreach ($info as $i){
824 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
828 $page = (empty($matches[1])) ? 0 : $matches[1];