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'])}%'
42 if(!empty($q['_to_base64']) && !empty($q['image_id'])) {
43 $i = DB_DataObject::factory("Images");
44 $i->get($q['image_id']);
45 $roo->jok($i->toBase64());
51 function checkPerm($lvl, $au)
53 // default permissons are to
54 // allow create / edit / if the user has
62 if ($o && method_exists($o, 'checkPerm')) {
63 // edit permissions on related object needed...
64 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
68 return true; //// ??? not really that safe...
72 function beforeInsert($q, $roo)
74 if (isset($q['_remote_upload'])) {
75 require_once 'System.php';
77 $tmpdir = System::mktemp("-d remote_upload");
79 $path = $tmpdir . '/' . basename($q['_remote_upload']);
81 if(!file_exists($path)){
82 file_put_contents($path, file_get_contents($q['_remote_upload']));
85 $imageInfo = getimagesize($path);
87 require_once 'File/MimeType.php';
88 $y = new File_MimeType();
89 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
91 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
92 rename($path,$path.".".$ext);
96 if (!$this->createFrom($path)) {
97 $roo->jerr("erro making image" . $q['_remote_upload']);
100 if(!empty($q['_return_after_create'])){
104 $roo->addEvent("ADD", $this, $this->toEventString());
106 $r = DB_DataObject::factory($this->tableName());
111 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
118 * create an email from file.
119 * these must have been set first.
123 function createFrom($file, $filename=false)
125 // copy the file into the storage area..
126 if (!file_exists($file) || !filesize($file)) {
127 $this->err = "File $file did not exist or is 0 size";
131 $filename = empty($filename) ? $file : $filename;
133 if (empty($this->mimetype)) {
134 require_once 'File/MimeType.php';
135 $y = new File_MimeType();
136 $this->mimetype = $y->fromFilename($filename);
139 $this->mimetype = strtolower($this->mimetype);
141 $mta = explode('/', $this->mimetype);
142 if (array_shift($mta) == 'image') {
144 $imgs = @getimagesize($file);
146 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
149 list($this->width , $this->height) = $imgs;
153 if($this->mimetype == 'application/pdf'){
154 $this->no_of_pages = $this->getPdfPages($file);
157 $this->filesize = filesize($file);
158 $this->created = date('Y-m-d H:i:s');
161 if (empty($this->filename)) {
162 $this->filename = basename($filename);
165 //DB_DataObject::debugLevel(1);
174 $f = $this->getStoreName();
176 if (!file_exists($dest)) {
177 // currently this is 0775 due to problems using shared hosing (FTP)
178 // it makes all the files unaccessable..
179 // you can normally solve this by giving the storedirectory better perms
180 // if needed on a dedicated server..
181 $oldumask = umask(0);
182 mkdir($dest, 0775, true);
193 // $this->createThumbnail(0,50);
199 * Calculate target file name
201 * @return - target file name
203 function getStoreName()
205 return self::staticGetStoreName($this);
209 static function staticGetStoreName($o)
211 $opts = HTML_FlexyFramework::get()->Pman;
212 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $o->filename);
213 return implode( '/', array(
214 $opts['storedir'], '_images_', date('Y/m', strtotime($o->created)), $o->id . '-'. $fn
219 * does the files exist?
223 return self::staticExists($this);
226 static function staticExists($o)
229 $ret = file_exists(self::staticGetStoreName($o));
231 return self::staticCanFix($o);
237 * the getStorename code got changed, and some old files may not end up with the correct name anymore.
238 * this tries to fix it.
243 return self::staticCanFix($this);
246 static function staticCanFix($o)
248 // look for the image in the folder, with matching id.
249 // this is problematic..
250 $fn = self::staticGetStoreName($o);
251 if (file_exists($fn . '-really-missing')) {
254 if (!file_exists(dirname($fn))) {
257 foreach( scandir(dirname($fn)) as $n) {
258 if (empty($n) || $n[0] == '.') {
261 $bits = explode('-', $n);
262 if ($bits[0] != $o->id) {
265 if (preg_match('/\.[0-9]+x[0-9]]+\.jpeg$/', $n)) {
268 copy(dirname($fn). '/'. $n, $fn);
272 // fixme - flag it as bad
273 touch($fn . '-really-missing');
278 * deletes all the image instances of it...
282 function beforeDelete($dependants_array, $roo)
285 if (!empty($dependants_array)) {
289 $opts = HTML_FlexyFramework::get()->Pman;
290 $deldir = $opts['storedir']. '/_deleted_images_';
292 if (!file_exists( $deldir )) {
293 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
296 $fn = $this->getStoreName();
299 if (file_exists($fn)) {
301 if (file_exists($deldir . '/'. $b)) {
304 rename($fn, $deldir .'/'. $b);
312 if (file_exists($d)) {
315 while (false !== ($fn = readdir($dh))) {
316 if (substr($fn, 0, strlen($b)) == $b) {
318 if (file_exists($deldir . '/'. $fn)) {
319 unlink($d. '/'. $fn);
322 if (file_exists($d. '/'. $fn)) {
323 rename($d. '/'. $fn, $deldir .'/'. $fn);
332 * check mimetype against type
333 * - eg. img.is(#image#)
338 if (empty($this->mimetype)) {
341 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
345 * onUpload (singlely attached image to a table)
348 function onUploadWithTbl($tbl, $fld)
350 if ( $tbl->__table == 'Images') {
351 return; // not upload to self...
353 if (empty($_FILES['imageUpload']['tmp_name']) ||
354 empty($_FILES['imageUpload']['name']) ||
355 empty($_FILES['imageUpload']['type'])
360 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
362 $image = DB_DataObject::factory('Images');
363 $image->get($tbl->$fld);
364 $image->beforeDelete();
368 $image = DB_DataObject::factory('Images');
369 $image->onid = $tbl->id;
370 $image->ontable = $tbl->__table;
371 $image->filename = $_FILES['imageUpload']['name'];
372 $image->mimetype = $_FILES['imageUpload']['type'];
374 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
378 $tbl->$fld = $image->id;
385 function onUpload($roo, $table = false, $file = false)
388 if ($table !== false) {
389 $this->ontable = $table->tableName();
390 $this->onid = $table->pid();
393 if ($file === false) {
394 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
397 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
398 if (empty($file['tmp_name']) ||
399 empty($file['name']) ||
404 0=>"There is no error, the file uploaded with success",
405 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
406 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
407 3=>"The uploaded file was only partially uploaded",
408 4=>"No file was uploaded",
409 6=>"Missing a temporary folder"
411 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
412 $this->err = "Missing file details : Error=". $estr;
417 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
419 $this->beforeDelete();
421 if ( empty($this->ontable)) {
422 $this->err = "Missing ontable";
426 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
427 // then its an upload
428 $img = DB_DataObject::factory('Images');
429 $img->onid = $this->onid;
430 $img->ontable = $this->ontable;
431 $img->imgtype = $this->imgtype;
434 while ($img->fetch()) {
435 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
437 $img->beforeDelete();
445 require_once 'File/MimeType.php';
446 $y = new File_MimeType();
447 $this->mimetype = $file['type'];
448 if (in_array($this->mimetype, array(
450 'application/octet-stream',
451 'image/x-png', // WTF does this?
452 'image/pjpeg', // WTF does this?
453 'application/x-apple-msg-attachment', /// apple doing it's magic...
454 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
455 'application/csv-tab-delimited-table', // windows again!!?
456 ))) { // weird tyeps..
457 $inf = pathinfo($file['name']);
458 $this->mimetype = $y->fromExt($inf['extension']);
462 $ext = $y->toExt(trim((string) $this->mimetype ));
464 $this->filename = empty($this->filename) ?
465 $file['name'] : ($this->filename .'.'. $ext);
469 if (!$this->createFrom($file['tmp_name'])) {
470 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
480 * return a list of images for an object, optionally with a mime regex.
481 * eg. '%/pdf' or 'image/%'
485 * $i = DB_DataObject::factory('Images');
486 * $i->imgtype = 'LOGO';
487 * $ar = $i->gather($somedataobject, 'image/%');
489 * @param {DB_DataObject} dataobject = the object to gather data on.
490 * @param {String} mimelike LIKE query to use for search
493 function gather($obj, $mime_like='', $opts=array())
495 //DB_DataObject::debugLevel(1);
496 if (empty($obj->id)) {
501 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
504 if (!empty($mime_like)) {
505 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
507 $c->orderBy('created DESC');
509 return $c->fetchAll();
514 * set or get the dataobject this image is associated with
515 * @param DB_DataObject $obj An object to associate this image with
516 * (does not store it - you need to call update() to do that)
517 * @return DB_DataObject the dataobject this image is attached to.
519 function object($obj=false)
521 if ($obj === false) {
522 if (empty($this->ontable) || empty($this->onid)) {
525 $ret = DB_DataObject::factory($this->ontable);
526 $ret->get($this->onid);
531 $this->ontable = $obj->tableName();
532 $this->onid = $obj->id; /// assumes our nice standard of using ids..
537 function toRooArray($req)
540 $ret= $this->toArray();
543 $ff = HTML_FlexyFramework::get();
546 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
547 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
549 if (!empty($req['query']['imagesize'])) {
550 // query/imageBaseURL ... depricated...? -- set it in config?
552 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
554 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
556 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
558 if (!empty($req['query']['imagesize'])) {
559 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
564 $ret['shorten_name'] = $this->shorten_name();
570 * URL - create a url for the image.
571 * size - use -1 to show full size.
572 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
576 function URL($size , $provider = '/Images/Thumb', $baseURL=false, $to_type=false)
579 return 'about:blank';
581 if (!$this->exists()) {
582 return 'about:missing';
585 $shorten_name = $this->shorten_name();
587 $ff = HTML_FlexyFramework::get();
588 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
589 if (preg_match('#^http[s]*://#', $provider)) {
594 $provider = preg_replace('#/Thumb$#', '', $provider);
596 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
599 //$size = max(100, (int) $size);
600 //$size = min(1024, (int) $size);
601 // the size should 200x150 to convert
602 $sizear = preg_split('/(x|c)/', $size);
603 if(!isset($sizear[1])){
604 $sizear[1] = 0; // 0x with '0' is a box? why
607 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
609 $fc = $this->toFileConvert();
612 $mt = $to_type === false ? $this->mimetype : $to_type;
613 if (!preg_match('#^image/#i',$mt)) {
617 $cn = $fc->convert($mt, $size);
618 $shorten_name = $this->shorten_name(basename($cn));
620 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
624 * tries to get an image from then URL - not always has based... - also from the normal url
626 function getFromHashURL($url)
629 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
631 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
633 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
635 } else if (preg_match('#images[^/]+/([0-9]+)/#i', $url, $matches)) {
636 // supports images.xxxxx.com/{number}/name...
639 if ($id === false || $id < 1) {
643 $img = DB_DAtaObject::Factory('images');
644 if ($img->get($id)) {
651 function shorten_name($fn = false)
653 if(empty($this->filename)) {
656 $fn = $fn === false ? $this->filename : $fn;
658 $filename = explode('.', $fn);
659 $ext = array_pop($filename);
660 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
662 if(strlen($name) > 32) {
663 $name = substr($name, 0, 32);
666 $shorten_name = "{$name}.{$ext}";
668 return $shorten_name;
671 * size could be 123x345
675 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
680 $sz = explode('x', $size);
683 if (!$this->id || empty($this->width)) {
685 $this->width = empty($sz[1]) ? $sx : $sz[1];
689 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
690 $sy = intval($ratio * $sx);
696 if (strlen($this->title)) {
697 $extra = ' title="'. htmlspecialchars($this->title) . '"';
700 return '<img src="' . $this->URL($size, $provider) . '"' .
702 ' width="'. $sx . '"' .
703 ' height="'. $sy . '">';
710 * #2142 [new] CMS - image link urls
715 function toLinkHTML($size, $provider = '/Images/Thumb')
717 if(empty($this->linkurl)){
718 return $this->toHTML($size, $provider = '/Images/Thumb');
721 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
727 * to Fileconvert object..
732 function toFileConvert()
734 $fn = $this->getStoreName();
736 require_once 'File/Convert.php';
737 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
744 require_once 'File/MimeType.php';
746 $y = new File_MimeType();
747 return $y->toExt($this->mimetype);
759 function setFromRoo($ar, $roo)
761 // not sure why we do this..
763 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
764 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
767 if ($this->find(true)) {
768 $roo->old = clone($this);
773 if (!empty($ar['_copy_from'])) {
775 if (!$this->checkPerm( 'A' , $roo->authUser)) {
776 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
779 $copy = DB_DataObject::factory('Images');
780 $copy->get($ar['_copy_from']);
781 $this->setFrom($copy->toArray());
783 $this->createFrom($copy->getStoreName());
785 $roo->addEvent("ADD", $this, $this->toEventString());
787 $r = DB_DataObject::factory($this->tableName());
793 $roo->jok($r->toRooArray($ar));
800 // FIXME - we should be checking perms here...
802 // this should be doign update
805 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
806 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
810 if (!isset($_FILES['imageUpload'])) {
811 return; // standard update...
815 // print_r(!$this->onUpload($this));
817 if ( !$this->onUpload($this)) {
818 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
821 $this->addEvent($ar, $roo);
823 $r = DB_DataObject::factory($this->tableName());
828 $roo->jok($r->toRooArray($ar));
832 function addEvent($ar, $roo)
834 $roo->addEvent("ADD", $this, $this->toEventString());
837 function toEventString()
840 //$p = DB_DataObject::factory($this->ontable);
842 // return "ERROR unknown table? {$this->ontable}";
846 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
847 //$p->toEventString();
850 function onUploadFromData($data, $roo)
853 $this->err = "Missing file details";
858 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
860 $this->beforeDelete();
863 if (empty($this->ontable)) {
864 $this->err = "Missing ontable";
868 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
869 // then its an upload
870 $img = DB_DataObject::factory('Images');
871 $img->onid = $this->onid;
872 $img->ontable = $this->ontable;
873 $img->imgtype = $this->imgtype;
876 while ($img->fetch()) {
877 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
879 $img->beforeDelete();
885 require_once 'File/MimeType.php';
886 $y = new File_MimeType();
888 if (in_array($this->mimetype, array(
890 'application/octet-stream',
891 'image/x-png', // WTF does this?
892 'image/pjpeg', // WTF does this?
893 'application/x-apple-msg-attachment', /// apple doing it's magic...
894 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
895 'application/csv-tab-delimited-table', // windows again!!?
896 ))) { // weird tyeps..
897 $inf = pathinfo($this->filename);
898 $this->mimetype = $y->fromExt($inf['extension']);
901 $ext = $y->toExt(trim((string) $this->mimetype ));
903 $explode_filename = explode('.', $this->filename);
904 if(array_pop($explode_filename) != $ext){
905 $this->filename = $this->filename .'.'. $ext;
908 if (!$this->createFromData($data)) {
916 function createFromData($data)
919 if (0 === strpos($data, "data:")) {
920 // data:image/png;base64,
921 $data = substr($data,5);
922 $bits = explode(";", $data);
923 $this->mimetype = $bits[0];
926 if (empty($this->filename)) {
927 require_once 'File/MimeType.php';
928 $y = new File_MimeType();
929 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
933 $this->mimetype = strtolower($this->mimetype);
934 if ($this->mimetype == 'image/jpg') {
935 $this->mimetype = 'image/jpeg';
939 $explode_mimetype = explode('/', $this->mimetype);
941 if (array_shift($explode_mimetype) == 'image') {
943 $imgs = @getimagesize('data://'. $data);
945 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
946 list($this->width , $this->height) = $imgs;
950 $this->created = date('Y-m-d H:i:s');
958 $f = $this->getStoreName();
960 if (!file_exists($dest)) {
961 $oldumask = umask(0);
962 mkdir($dest, 0775, true);
966 file_put_contents($f, file_get_contents("data://" . $data));
970 $this->filesize = filesize($f);
972 if($this->mimetype == 'application/pdf'){
973 $this->no_of_pages = $this->getPdfPages($f);
982 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
984 if(!preg_match('/^image\//', $this->mimetype)){
988 $file = $this->getStoreName();
990 if(!file_exists($file)){
994 $data = file_get_contents($file);
996 if(!empty($scaleWidth) || !empty($scaleHeight)){
997 $data = $this->scale(false, $scaleWidth, $scaleHeight);
1001 $data = $this->rotate($data);
1004 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
1009 function getPdfPages($file)
1011 require_once 'System.php';
1015 $pdfinfo = System::which('pdfinfo');
1017 if (!file_exists($file) || empty($pdfinfo)) {
1021 $cmd = "{$pdfinfo} {$file}";
1025 $info = explode("\n", $ret);
1027 foreach ($info as $i){
1029 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
1033 $page = (empty($matches[1])) ? 0 : $matches[1];
1039 function rotate($imageBlob = false)
1041 if(empty($imageBlob)){
1042 $imagick = new Imagick($this->getStoreName());
1044 $imagick = new Imagick();
1045 $imagick->readImageBlob($imageBlob);
1048 $orientation = $imagick->getImageOrientation();
1050 switch($orientation) {
1051 case Imagick::ORIENTATION_BOTTOMRIGHT:
1052 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
1055 case Imagick::ORIENTATION_RIGHTTOP:
1056 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
1059 case Imagick::ORIENTATION_LEFTBOTTOM:
1060 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
1064 return $imagick->getImageBlob();
1067 function scale($imageBlob = false, $width = 0, $height = 0)
1069 if(empty($imageBlob)){
1070 $imagick = new Imagick($this->getStoreName());
1072 $imagick = new Imagick();
1073 $imagick->readImageBlob($imageBlob);
1076 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1078 return $imagick->getImageBlob();