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 */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['filename'])){
38 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
45 function checkPerm($lvl, $au)
47 // default permissons are to
48 // allow create / edit / if the user has
56 if (method_exists($o, 'checkPerm')) {
57 // edit permissions on related object needed...
58 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
62 return true; //// ??? not really that safe...
66 function beforeInsert($q, $roo)
68 if (isset($q['_remote_upload'])) {
69 require_once 'System.php';
71 $tmpdir = System::mktemp("-d remote_upload");
73 $path = $tmpdir . '/' . basename($q['_remote_upload']);
75 if(!file_exists($path)){
76 file_put_contents($path, file_get_contents($q['_remote_upload']));
79 $imageInfo = getimagesize($path);
81 require_once 'File/MimeType.php';
82 $y = new File_MimeType();
83 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
85 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
86 rename($path,$path.".".$ext);
90 if (!$this->createFrom($path)) {
91 $roo->jerr("erro making image" . $q['_remote_upload']);
94 if(!empty($q['_return_after_create'])){
98 $roo->addEvent("ADD", $this, $this->toEventString());
100 $r = DB_DataObject::factory($this->tableName());
105 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
112 * create an email from file.
113 * these must have been set first.
117 function createFrom($file, $filename=false)
119 // copy the file into the storage area..
120 if (!file_exists($file) || !filesize($file)) {
121 $this->err = "File $file did not exist or is 0 size";
125 $filename = empty($filename) ? $file : $filename;
127 if (empty($this->mimetype)) {
128 require_once 'File/MimeType.php';
129 $y = new File_MimeType();
130 $this->mimetype = $y->fromFilename($filename);
133 $this->mimetype = strtolower($this->mimetype);
135 $mta = explode('/', $this->mimetype);
136 if (array_shift($mta) == 'image') {
138 $imgs = @getimagesize($file);
140 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
143 list($this->width , $this->height) = $imgs;
147 if($this->mimetype == 'application/pdf'){
148 $this->no_of_pages = $this->getPdfPages($file);
151 $this->filesize = filesize($file);
152 $this->created = date('Y-m-d H:i:s');
155 if (empty($this->filename)) {
156 $this->filename = basename($filename);
159 //DB_DataObject::debugLevel(1);
168 $f = $this->getStoreName();
170 if (!file_exists($dest)) {
171 // currently this is 0775 due to problems using shared hosing (FTP)
172 // it makes all the files unaccessable..
173 // you can normally solve this by giving the storedirectory better perms
174 // if needed on a dedicated server..
175 $oldumask = umask(0);
176 mkdir($dest, 0775, true);
187 // $this->createThumbnail(0,50);
193 * Calculate target file name
195 * @return - target file name
197 function getStoreName()
199 $opts = HTML_FlexyFramework::get()->Pman;
200 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
201 return implode( '/', array(
202 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
208 * does the files exist?
212 return file_exists($this->getStoreName());
217 * deletes all the image instances of it...
221 function beforeDelete($dependants_array, $roo)
224 if (!empty($dependants_array)) {
228 $opts = HTML_FlexyFramework::get()->Pman;
229 $deldir = $opts['storedir']. '/_deleted_images_';
231 if (!file_exists( $deldir )) {
232 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
235 $fn = $this->getStoreName();
237 if (file_exists($fn)) {
239 if (file_exists($deldir . '/'. $b)) {
242 rename($fn, $deldir .'/'. $b);
250 if (file_exists($d)) {
253 while (false !== ($fn = readdir($dh))) {
254 if (substr($fn, 0, strlen($b)) == $b) {
256 if (file_exists($deldir . '/'. $fn)) {
257 unlink($d. '/'. $fn);
260 rename($d. '/'. $fn, $deldir .'/'. $fn);
268 * check mimetype against type
269 * - eg. img.is(#image#)
274 if (empty($this->mimetype)) {
277 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
281 * onUpload (singlely attached image to a table)
284 function onUploadWithTbl($tbl, $fld)
286 if ( $tbl->__table == 'Images') {
287 return; // not upload to self...
289 if (empty($_FILES['imageUpload']['tmp_name']) ||
290 empty($_FILES['imageUpload']['name']) ||
291 empty($_FILES['imageUpload']['type'])
296 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
298 $image = DB_DataObject::factory('Images');
299 $image->get($tbl->$fld);
300 $image->beforeDelete();
304 $image = DB_DataObject::factory('Images');
305 $image->onid = $tbl->id;
306 $image->ontable = $tbl->__table;
307 $image->filename = $_FILES['imageUpload']['name'];
308 $image->mimetype = $_FILES['imageUpload']['type'];
310 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
314 $tbl->$fld = $image->id;
321 function onUpload($roo, $table = false, $file = false)
324 if ($table !== false) {
325 $this->ontable = $table->tableName();
326 $this->onid = $table->pid();
329 if ($file === false) {
330 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
333 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
334 if (empty($file['tmp_name']) ||
335 empty($file['name']) ||
340 0=>"There is no error, the file uploaded with success",
341 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
342 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
343 3=>"The uploaded file was only partially uploaded",
344 4=>"No file was uploaded",
345 6=>"Missing a temporary folder"
347 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
348 $this->err = "Missing file details : Error=". $estr;
353 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
355 $this->beforeDelete();
357 if ( empty($this->ontable)) {
358 $this->err = "Missing ontable";
362 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
363 // then its an upload
364 $img = DB_DataObject::factory('Images');
365 $img->onid = $this->onid;
366 $img->ontable = $this->ontable;
367 $img->imgtype = $this->imgtype;
370 while ($img->fetch()) {
371 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
373 $img->beforeDelete();
381 require_once 'File/MimeType.php';
382 $y = new File_MimeType();
383 $this->mimetype = $file['type'];
384 if (in_array($this->mimetype, array(
386 'application/octet-stream',
387 'image/x-png', // WTF does this?
388 'image/pjpeg', // WTF does this?
389 'application/x-apple-msg-attachment', /// apple doing it's magic...
390 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
391 'application/csv-tab-delimited-table', // windows again!!?
392 ))) { // weird tyeps..
393 $inf = pathinfo($file['name']);
394 $this->mimetype = $y->fromExt($inf['extension']);
398 $ext = $y->toExt(trim((string) $this->mimetype ));
400 $this->filename = empty($this->filename) ?
401 $file['name'] : ($this->filename .'.'. $ext);
405 if (!$this->createFrom($file['tmp_name'])) {
406 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
416 * return a list of images for an object, optionally with a mime regex.
417 * eg. '%/pdf' or 'image/%'
421 * $i = DB_DataObject::factory('Images');
422 * $i->imgtype = 'LOGO';
423 * $ar = $i->gather($somedataobject, 'image/%');
425 * @param {DB_DataObject} dataobject = the object to gather data on.
426 * @param {String} mimelike LIKE query to use for search
429 function gather($obj, $mime_like='', $opts=array())
431 //DB_DataObject::debugLevel(1);
432 if (empty($obj->id)) {
437 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
440 if (!empty($mime_like)) {
441 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
443 $c->orderBy('created DESC');
445 return $c->fetchAll();
450 * set or get the dataobject this image is associated with
451 * @param DB_DataObject $obj An object to associate this image with
452 * (does not store it - you need to call update() to do that)
453 * @return DB_DataObject the dataobject this image is attached to.
455 function object($obj=false)
457 if ($obj === false) {
458 if (empty($this->ontable) || empty($this->onid)) {
461 $ret = DB_DataObject::factory($this->ontable);
462 $ret->get($this->onid);
467 $this->ontable = $obj->tableName();
468 $this->onid = $obj->id; /// assumes our nice standard of using ids..
473 function toRooArray($req)
476 $ret= $this->toArray();
479 $ff = HTML_FlexyFramework::get();
482 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
483 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
485 if (!empty($req['query']['imagesize'])) {
486 // query/imageBaseURL ... depricated...? -- set it in config?
488 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
490 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
492 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
494 if (!empty($req['query']['imagesize'])) {
495 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
500 $ret['shorten_name'] = $ret['filename'] = $this->shorten_name();
506 * URL - create a url for the image.
507 * size - use -1 to show full size.
508 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
512 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
515 return 'about:blank';
517 if (!$this->exists()) {
518 return 'about:missing';
521 $shorten_name = $this->shorten_name();
523 $ff = HTML_FlexyFramework::get();
524 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
525 if (preg_match('#^http[s]*://#', $provider)) {
530 $provider = preg_replace('#/Thumb$#', '', $provider);
532 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
535 //$size = max(100, (int) $size);
536 //$size = min(1024, (int) $size);
537 // the size should 200x150 to convert
538 $sizear = preg_split('/(x|c)/', $size);
539 if(!isset($sizear[1])){
540 $sizear[1] = 0; // 0x with '0' is a box? why
543 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
545 $fc = $this->toFileConvert();
548 $mt = $this->mimetype;
549 if (!preg_match('#^image/#i',$mt)) {
553 $fc->convert($mt, $size);
555 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
558 function getFromHashURL($url)
561 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
563 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
565 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
569 if ($id === false || $id < 1) {
573 $img = DB_DAtaObject::Factory('images');
574 if ($img->get($id)) {
581 function shorten_name()
583 if(empty($this->filename)) {
587 $filename = explode('.', $this->filename);
588 $ext = array_pop($filename);
589 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
591 if(strlen($name) > 32) {
592 $name = substr($name, 0, 32);
595 $shorten_name = "{$name}.{$ext}";
597 return $shorten_name;
600 * size could be 123x345
604 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
609 $sz = explode('x', $size);
612 if (!$this->id || empty($this->width)) {
614 $this->width = empty($sz[1]) ? $sx : $sz[1];
618 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
619 $sy = intval($ratio * $sx);
625 if (strlen($this->title)) {
626 $extra = ' title="'. htmlspecialchars($this->title) . '"';
629 return '<img src="' . $this->URL($size, $provider) . '"' .
631 ' width="'. $sx . '"' .
632 ' height="'. $sy . '">';
639 * #2142 [new] CMS - image link urls
644 function toLinkHTML($size, $provider = '/Images/Thumb')
646 if(empty($this->linkurl)){
647 return $this->toHTML($size, $provider = '/Images/Thumb');
650 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
656 * to Fileconvert object..
661 function toFileConvert()
663 require_once 'File/Convert.php';
664 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
671 require_once 'File/MimeType.php';
673 $y = new File_MimeType();
674 return $y->toExt($this->mimetype);
686 function setFromRoo($ar, $roo)
688 // not sure why we do this..
690 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
691 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
694 if ($this->find(true)) {
695 $roo->old = clone($this);
700 if (!empty($ar['_copy_from'])) {
702 if (!$this->checkPerm( 'A' , $roo->authUser)) {
703 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
706 $copy = DB_DataObject::factory('Images');
707 $copy->get($ar['_copy_from']);
708 $this->setFrom($copy->toArray());
710 $this->createFrom($copy->getStoreName());
712 $roo->addEvent("ADD", $this, $this->toEventString());
714 $r = DB_DataObject::factory($this->tableName());
720 $roo->jok($r->toRooArray($ar));
727 // FIXME - we should be checking perms here...
729 // this should be doign update
732 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
733 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
737 if (!isset($_FILES['imageUpload'])) {
738 return; // standard update...
742 // print_r(!$this->onUpload($this));
744 if ( !$this->onUpload($this)) {
745 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
748 $this->addEvent($ar, $roo);
750 $r = DB_DataObject::factory($this->tableName());
755 $roo->jok($r->toRooArray($ar));
759 function addEvent($ar, $roo)
761 $roo->addEvent("ADD", $this, $this->toEventString());
764 function toEventString()
767 //$p = DB_DataObject::factory($this->ontable);
769 // return "ERROR unknown table? {$this->ontable}";
773 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
774 //$p->toEventString();
777 function onUploadFromData($data, $roo)
780 $this->err = "Missing file details";
785 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
787 $this->beforeDelete();
790 if (empty($this->ontable)) {
791 $this->err = "Missing ontable";
795 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
796 // then its an upload
797 $img = DB_DataObject::factory('Images');
798 $img->onid = $this->onid;
799 $img->ontable = $this->ontable;
800 $img->imgtype = $this->imgtype;
803 while ($img->fetch()) {
804 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
806 $img->beforeDelete();
812 require_once 'File/MimeType.php';
813 $y = new File_MimeType();
815 if (in_array($this->mimetype, array(
817 'application/octet-stream',
818 'image/x-png', // WTF does this?
819 'image/pjpeg', // WTF does this?
820 'application/x-apple-msg-attachment', /// apple doing it's magic...
821 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
822 'application/csv-tab-delimited-table', // windows again!!?
823 ))) { // weird tyeps..
824 $inf = pathinfo($this->filename);
825 $this->mimetype = $y->fromExt($inf['extension']);
828 $ext = $y->toExt(trim((string) $this->mimetype ));
830 $explode_filename = explode('.', $this->filename);
831 if(array_pop($explode_filename) != $ext){
832 $this->filename = $this->filename .'.'. $ext;
835 if (!$this->createFromData($data)) {
843 function createFromData($data)
846 if (0 === strpos($data, "data:")) {
847 // data:image/png;base64,
848 $data = substr($data,5);
849 $bits = explode(";", $data);
850 $this->mimetype = $bits[0];
853 if (empty($this->filename)) {
854 require_once 'File/MimeType.php';
855 $y = new File_MimeType();
856 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
860 $this->mimetype = strtolower($this->mimetype);
862 $explode_mimetype = explode('/', $this->mimetype);
864 if (array_shift($explode_mimetype) == 'image') {
866 $imgs = @getimagesize('data://'. $data);
868 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
869 list($this->width , $this->height) = $imgs;
873 $this->created = date('Y-m-d H:i:s');
881 $f = $this->getStoreName();
883 if (!file_exists($dest)) {
884 $oldumask = umask(0);
885 mkdir($dest, 0775, true);
889 file_put_contents($f, file_get_contents("data://" . $data));
893 $this->filesize = filesize($f);
895 if($this->mimetype == 'application/pdf'){
896 $this->no_of_pages = $this->getPdfPages($f);
905 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
907 if(!preg_match('/^image\//', $this->mimetype)){
911 $file = $this->getStoreName();
913 if(!file_exists($file)){
917 $data = file_get_contents($file);
919 if(!empty($scaleWidth) || !empty($scaleHeight)){
920 $data = $this->scale(false, $scaleWidth, $scaleHeight);
924 $data = $this->rotate($data);
927 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
932 function getPdfPages($file)
934 require_once 'System.php';
938 $pdfinfo = System::which('pdfinfo');
940 if (!file_exists($file) || empty($pdfinfo)) {
944 $cmd = "{$pdfinfo} {$file}";
948 $info = explode("\n", $ret);
950 foreach ($info as $i){
952 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
956 $page = (empty($matches[1])) ? 0 : $matches[1];
962 function rotate($imageBlob = false)
964 if(empty($imageBlob)){
965 $imagick = new Imagick($this->getStoreName());
967 $imagick = new Imagick();
968 $imagick->readImageBlob($imageBlob);
971 $orientation = $imagick->getImageOrientation();
973 switch($orientation) {
974 case Imagick::ORIENTATION_BOTTOMRIGHT:
975 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
978 case Imagick::ORIENTATION_RIGHTTOP:
979 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
982 case Imagick::ORIENTATION_LEFTBOTTOM:
983 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
987 return $imagick->getImageBlob();
990 function scale($imageBlob = false, $width = 0, $height = 0)
992 if(empty($imageBlob)){
993 $imagick = new Imagick($this->getStoreName());
995 $imagick = new Imagick();
996 $imagick->readImageBlob($imageBlob);
999 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1001 return $imagick->getImageBlob();