plugins/gallery/functions.php
changeset 42 7c6e2e97aa08
parent 38 512951548faa
child 45 740bbe1f4dd5
equal deleted inserted replaced
41:0944c9354e9c 42:7c6e2e97aa08
    18  * @return string
    18  * @return string
    19  */
    19  */
    20  
    20  
    21 function gallery_make_filename($length = 24)
    21 function gallery_make_filename($length = 24)
    22 {
    22 {
    23   $valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    23 	$valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    24   $valid_chars = enano_str_split($valid_chars);
    24 	$valid_chars = enano_str_split($valid_chars);
    25   $ret = '';
    25 	$ret = '';
    26   for ( $i = 0; $i < $length; $i++ )
    26 	for ( $i = 0; $i < $length; $i++ )
    27   {
    27 	{
    28     $ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
    28 		$ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
    29   }
    29 	}
    30   return $ret;
    30 	return $ret;
    31 }
    31 }
    32 
    32 
    33 /**
    33 /**
    34  * Returns the extension of a file.
    34  * Returns the extension of a file.
    35  * @param string file
    35  * @param string file
    36  * @return string
    36  * @return string
    37  */
    37  */
    38 
    38 
    39 function get_file_extension($file)
    39 function get_file_extension($file)
    40 {
    40 {
    41   return substr($file, ( strrpos($file, '.') + 1 ));
    41 	return substr($file, ( strrpos($file, '.') + 1 ));
    42 }
    42 }
    43 
    43 
    44 /**
    44 /**
    45  * For a given image ID, return the folder hierarchy.
    45  * For a given image ID, return the folder hierarchy.
    46  * @param int The image ID
    46  * @param int The image ID
    47  * @return array
    47  * @return array
    48  */
    48  */
    49 
    49 
    50 function gallery_imgid_to_folder($img_id)
    50 function gallery_imgid_to_folder($img_id)
    51 {
    51 {
    52   global $db, $session, $paths, $template, $plugins; // Common objects
    52 	global $db, $session, $paths, $template, $plugins; // Common objects
    53   
    53 	
    54   if ( !is_int($img_id) )
    54 	if ( !is_int($img_id) )
    55     return array();
    55 		return array();
    56   
    56 	
    57   $img_id = strval($img_id);
    57 	$img_id = strval($img_id);
    58   $ret = array();
    58 	$ret = array();
    59   
    59 	
    60   $sanity = 0;
    60 	$sanity = 0;
    61   $sanity_stack = array();
    61 	$sanity_stack = array();
    62   
    62 	
    63   while(true)
    63 	while(true)
    64   {
    64 	{
    65     $sanity++;
    65 		$sanity++;
    66     $q = $db->sql_query('SELECT img_title, img_id, folder_parent FROM '.table_prefix.'gallery WHERE img_id=' . $img_id . ';');
    66 		$q = $db->sql_query('SELECT img_title, img_id, folder_parent FROM '.table_prefix.'gallery WHERE img_id=' . $img_id . ';');
    67     if ( !$q )
    67 		if ( !$q )
    68       $db->_die();
    68 			$db->_die();
    69     $row = $db->fetchrow();
    69 		$row = $db->fetchrow();
    70     if ( !$row )
    70 		if ( !$row )
    71     {
    71 		{
    72       break;
    72 			break;
    73     }
    73 		}
    74     if ( $sanity > 1 )
    74 		if ( $sanity > 1 )
    75     {
    75 		{
    76       $ret[] = $row['img_title'];
    76 			$ret[] = $row['img_title'];
    77     }
    77 		}
    78     if ( !$row['folder_parent'] )
    78 		if ( !$row['folder_parent'] )
    79     {
    79 		{
    80       break;
    80 			break;
    81     }
    81 		}
    82     if ( in_array($row['img_id'], $sanity_stack) )
    82 		if ( in_array($row['img_id'], $sanity_stack) )
    83       return array('Infinite loop');
    83 			return array('Infinite loop');
    84     $sanity_stack[] = $row['img_id'];
    84 		$sanity_stack[] = $row['img_id'];
    85     $img_id = $row['folder_parent'];
    85 		$img_id = $row['folder_parent'];
    86   }
    86 	}
    87   return $ret;
    87 	return $ret;
    88 }
    88 }
    89 
    89 
    90 /**
    90 /**
    91  * Generates a hierarchy of Gallery folders.
    91  * Generates a hierarchy of Gallery folders.
    92  * @return array
    92  * @return array
    93  */
    93  */
    94 
    94 
    95 function gallery_folder_hierarchy()
    95 function gallery_folder_hierarchy()
    96 {
    96 {
    97   global $db, $session, $paths, $template, $plugins; // Common objects
    97 	global $db, $session, $paths, $template, $plugins; // Common objects
    98   
    98 	
    99   $q = $db->sql_query('SELECT img_id, img_title, folder_parent FROM '.table_prefix.'gallery WHERE is_folder=1');
    99 	$q = $db->sql_query('SELECT img_id, img_title, folder_parent FROM '.table_prefix.'gallery WHERE is_folder=1');
   100   if ( !$q )
   100 	if ( !$q )
   101     $db->_die();
   101 		$db->_die();
   102   
   102 	
   103   if ( $db->numrows() < 1 )
   103 	if ( $db->numrows() < 1 )
   104   {
   104 	{
   105     return array('_id' => 'NULL');
   105 		return array('_id' => 'NULL');
   106   }
   106 	}
   107   
   107 	
   108   $lookup_table = array();
   108 	$lookup_table = array();
   109   $hier = array('_id' => 'NULL');
   109 	$hier = array('_id' => 'NULL');
   110   $orphans = array();
   110 	$orphans = array();
   111   $persist_orphans = array();
   111 	$persist_orphans = array();
   112   
   112 	
   113   while ( $row = $db->fetchrow() )
   113 	while ( $row = $db->fetchrow() )
   114   {
   114 	{
   115     if ( !$row['folder_parent'] )
   115 		if ( !$row['folder_parent'] )
   116     {
   116 		{
   117       // root-level folder
   117 			// root-level folder
   118       $hier[ $row['img_title'] ] = array('_id' => $row['img_id']);
   118 			$hier[ $row['img_title'] ] = array('_id' => $row['img_id']);
   119       $lookup_table[$row['img_id']] =& $hier[ $row['img_title'] ];
   119 			$lookup_table[$row['img_id']] =& $hier[ $row['img_title'] ];
   120     }
   120 		}
   121     else if ( $row['folder_parent'] && isset($lookup_table[$row['folder_parent']]) )
   121 		else if ( $row['folder_parent'] && isset($lookup_table[$row['folder_parent']]) )
   122     {
   122 		{
   123       // child folder, parent is resolved
   123 			// child folder, parent is resolved
   124       $lookup_table[ $row['folder_parent'] ][ $row['img_title'] ] = array('_id' => $row['img_id']);
   124 			$lookup_table[ $row['folder_parent'] ][ $row['img_title'] ] = array('_id' => $row['img_id']);
   125       $lookup_table[ $row['img_id'] ] =& $lookup_table[ $row['folder_parent'] ][ $row['img_title'] ];
   125 			$lookup_table[ $row['img_id'] ] =& $lookup_table[ $row['folder_parent'] ][ $row['img_title'] ];
   126     }
   126 		}
   127     else if ( $row['folder_parent'] && !isset($lookup_table[$row['folder_parent']]) )
   127 		else if ( $row['folder_parent'] && !isset($lookup_table[$row['folder_parent']]) )
   128     {
   128 		{
   129       // child folder, orphan as of yet
   129 			// child folder, orphan as of yet
   130       $orphans[] = $row;
   130 			$orphans[] = $row;
   131     }
   131 		}
   132   }
   132 	}
   133   
   133 	
   134   // Resolve orphans
   134 	// Resolve orphans
   135   do
   135 	do
   136   {
   136 	{
   137     $persist_orphans = array();
   137 		$persist_orphans = array();
   138     while ( count($orphans) > 0 )
   138 		while ( count($orphans) > 0 )
   139     {
   139 		{
   140       $orphan =& $orphans[ ( count($orphans) - 1 ) ];
   140 			$orphan =& $orphans[ ( count($orphans) - 1 ) ];
   141       if ( isset($lookup_table[$orphan['folder_parent']]) )
   141 			if ( isset($lookup_table[$orphan['folder_parent']]) )
   142       {
   142 			{
   143         $lookup_table[ $orphan['folder_parent'] ][ $orphan['img_title'] ] = array('_id' => $orphan['img_id']);
   143 				$lookup_table[ $orphan['folder_parent'] ][ $orphan['img_title'] ] = array('_id' => $orphan['img_id']);
   144         $lookup_table[ $orphan['img_id'] ] =& $lookup_table[ $orphan['folder_parent'] ][ $orphan['img_title'] ];
   144 				$lookup_table[ $orphan['img_id'] ] =& $lookup_table[ $orphan['folder_parent'] ][ $orphan['img_title'] ];
   145       }
   145 			}
   146       else
   146 			else
   147       {
   147 			{
   148         $persist_orphans[] = $orphans[ ( count($orphans) - 1 ) ];
   148 				$persist_orphans[] = $orphans[ ( count($orphans) - 1 ) ];
   149         //echo 'BUG: ' . htmlspecialchars($orphan['img_title']) . ' (' . $orphan['img_id'] . ') is an orphan folder (parent is ' . $orphan['folder_parent'] . '); placing in root<br />';
   149 				//echo 'BUG: ' . htmlspecialchars($orphan['img_title']) . ' (' . $orphan['img_id'] . ') is an orphan folder (parent is ' . $orphan['folder_parent'] . '); placing in root<br />';
   150         // $hier[ $orphan['img_title'] ] = array();
   150 				// $hier[ $orphan['img_title'] ] = array();
   151         // $lookup_table[$orphan['img_id']] =& $hier[ $orphan['img_title'] ];
   151 				// $lookup_table[$orphan['img_id']] =& $hier[ $orphan['img_title'] ];
   152       }
   152 			}
   153       unset($orphan, $orphans[ ( count($orphans) - 1 ) ]);
   153 			unset($orphan, $orphans[ ( count($orphans) - 1 ) ]);
   154     }
   154 		}
   155     $orphans = $persist_orphans;
   155 		$orphans = $persist_orphans;
   156     //die('insanity:<pre>'.print_r($hier,true).print_r($lookup_table,true).print_r($persist_orphans,true).'</pre>');
   156 		//die('insanity:<pre>'.print_r($hier,true).print_r($lookup_table,true).print_r($persist_orphans,true).'</pre>');
   157   }
   157 	}
   158   while ( count($persist_orphans) > 0 );
   158 	while ( count($persist_orphans) > 0 );
   159   
   159 	
   160   return $hier;
   160 	return $hier;
   161   
   161 	
   162 }
   162 }
   163 
   163 
   164 /**
   164 /**
   165  * Generates HTML for a folder selector.
   165  * Generates HTML for a folder selector.
   166  * @param string The form field name, defaults to folder_id.
   166  * @param string The form field name, defaults to folder_id.
   168  * @return string
   168  * @return string
   169  */
   169  */
   170 
   170 
   171 function gallery_hier_formfield($field_name = 'folder_id', $autosel = true)
   171 function gallery_hier_formfield($field_name = 'folder_id', $autosel = true)
   172 {
   172 {
   173   $hier = gallery_folder_hierarchy();
   173 	$hier = gallery_folder_hierarchy();
   174   $img_join      = scriptPath . '/images/icons/joinbottom.gif';
   174 	$img_join      = scriptPath . '/images/icons/joinbottom.gif';
   175   $img_join_term = scriptPath . '/images/icons/join.gif';
   175 	$img_join_term = scriptPath . '/images/icons/join.gif';
   176   $img_line      = scriptPath . '/images/icons/line.gif';
   176 	$img_line      = scriptPath . '/images/icons/line.gif';
   177   $img_empty     = scriptPath . '/images/icons/empty.gif';
   177 	$img_empty     = scriptPath . '/images/icons/empty.gif';
   178   
   178 	
   179   $html = _gallery_hier_form_inner($hier, '<Root>', $field_name, -1, array(), $img_join, $img_join_term, $img_line, $img_empty, $autosel);
   179 	$html = _gallery_hier_form_inner($hier, '<Root>', $field_name, -1, array(), $img_join, $img_join_term, $img_line, $img_empty, $autosel);
   180   
   180 	
   181   return $html;
   181 	return $html;
   182 }
   182 }
   183 
   183 
   184 // 
   184 // 
   185 
   185 
   186 /**
   186 /**
   188  * @access private
   188  * @access private
   189  */
   189  */
   190 
   190 
   191 function _gallery_hier_form_inner($el, $name, $fname, $depth, $depth_img, $img_join, $img_join_term, $img_line, $img_empty, $sel = false)
   191 function _gallery_hier_form_inner($el, $name, $fname, $depth, $depth_img, $img_join, $img_join_term, $img_line, $img_empty, $sel = false)
   192 {
   192 {
   193   $html = '';
   193 	$html = '';
   194   foreach ( $depth_img as $sw )
   194 	foreach ( $depth_img as $sw )
   195     $html .= '<img alt="  " src="' . $sw . '" />';
   195 		$html .= '<img alt="  " src="' . $sw . '" />';
   196   
   196 	
   197   $html .= '<label><input ' . ( $sel ? 'checked="checked"' : '' ) . ' type="radio" name="' . $fname . '" value="' . $el['_id'] . '" /> ' . htmlspecialchars($name) . '</label><br />';
   197 	$html .= '<label><input ' . ( $sel ? 'checked="checked"' : '' ) . ' type="radio" name="' . $fname . '" value="' . $el['_id'] . '" /> ' . htmlspecialchars($name) . '</label><br />';
   198   
   198 	
   199   if ( count($el) > 1 )
   199 	if ( count($el) > 1 )
   200   {
   200 	{
   201     // Writing this image logic sucked.
   201 		// Writing this image logic sucked.
   202     $count = 0;
   202 		$count = 0;
   203     foreach ( $el as $key => $el_lower )
   203 		foreach ( $el as $key => $el_lower )
   204     {
   204 		{
   205       $count++;
   205 			$count++;
   206       if ( $key == '_id' )
   206 			if ( $key == '_id' )
   207         continue;
   207 				continue;
   208       $depth_mod = $depth_img;
   208 			$depth_mod = $depth_img;
   209       $last = ( $count == count($el) );
   209 			$last = ( $count == count($el) );
   210       
   210 			
   211       for ( $i = 0; $i < count($depth_mod); $i++ )
   211 			for ( $i = 0; $i < count($depth_mod); $i++ )
   212       {
   212 			{
   213         if ( $depth_mod[$i] == $img_join_term || $depth_mod[$i] == $img_empty )
   213 				if ( $depth_mod[$i] == $img_join_term || $depth_mod[$i] == $img_empty )
   214           $depth_mod[$i] = $img_empty;
   214 					$depth_mod[$i] = $img_empty;
   215         else
   215 				else
   216           $depth_mod[$i] = $img_line;
   216 					$depth_mod[$i] = $img_line;
   217       }
   217 			}
   218       
   218 			
   219       if ( $last )
   219 			if ( $last )
   220         $depth_mod[] = $img_join_term;
   220 				$depth_mod[] = $img_join_term;
   221       else
   221 			else
   222         $depth_mod[] = $img_join;
   222 				$depth_mod[] = $img_join;
   223       
   223 			
   224       $html .= _gallery_hier_form_inner($el_lower, $key, $fname, ( $depth + 1 ), $depth_mod, $img_join, $img_join_term, $img_line, $img_empty);
   224 			$html .= _gallery_hier_form_inner($el_lower, $key, $fname, ( $depth + 1 ), $depth_mod, $img_join, $img_join_term, $img_line, $img_empty);
   225     }
   225 		}
   226   }
   226 	}
   227   return $html;
   227 	return $html;
   228 }
   228 }
   229 
   229 
   230 /**
   230 /**
   231  * Returns an array containing the IDs of all of the given folder ID's children. Recursive function.
   231  * Returns an array containing the IDs of all of the given folder ID's children. Recursive function.
   232  * @param int ID of folder
   232  * @param int ID of folder
   233  */
   233  */
   234 
   234 
   235 function gal_fetch_all_children($id)
   235 function gal_fetch_all_children($id)
   236 {
   236 {
   237   global $db, $session, $paths, $template, $plugins; // Common objects
   237 	global $db, $session, $paths, $template, $plugins; // Common objects
   238   
   238 	
   239   if ( !is_int($id) )
   239 	if ( !is_int($id) )
   240   {
   240 	{
   241     die('not int');
   241 		die('not int');
   242     return false;
   242 		return false;
   243   }
   243 	}
   244   
   244 	
   245   $children = array();
   245 	$children = array();
   246   
   246 	
   247   $q = $db->sql_query('SELECT img_id,is_folder FROM '.table_prefix.'gallery WHERE folder_parent=' . $id . ';');
   247 	$q = $db->sql_query('SELECT img_id,is_folder FROM '.table_prefix.'gallery WHERE folder_parent=' . $id . ';');
   248   if ( !$q )
   248 	if ( !$q )
   249     $db->_die();
   249 		$db->_die();
   250   if ( $db->numrows() < 1 )
   250 	if ( $db->numrows() < 1 )
   251   {
   251 	{
   252     return $children;
   252 		return $children;
   253   }
   253 	}
   254   $folders = array();
   254 	$folders = array();
   255   while ( $row = $db->fetchrow() )
   255 	while ( $row = $db->fetchrow() )
   256   {
   256 	{
   257     $children[] = intval($row['img_id']);
   257 		$children[] = intval($row['img_id']);
   258     if ( $row['is_folder'] == 1 )
   258 		if ( $row['is_folder'] == 1 )
   259       $folders[] = intval($row['img_id']);
   259 			$folders[] = intval($row['img_id']);
   260   }
   260 	}
   261   foreach ( $folders as $folder )
   261 	foreach ( $folders as $folder )
   262   {
   262 	{
   263     $grandchildren = gal_fetch_all_children($folder);
   263 		$grandchildren = gal_fetch_all_children($folder);
   264     if ( $grandchildren === false )
   264 		if ( $grandchildren === false )
   265     {
   265 		{
   266       return false;
   266 			return false;
   267     }
   267 		}
   268     $children = array_merge($children, $grandchildren);
   268 		$children = array_merge($children, $grandchildren);
   269   }
   269 	}
   270   
   270 	
   271   return $children;
   271 	return $children;
   272   
   272 	
   273 }
   273 }
   274 
   274 
   275 /**
   275 /**
   276  * Lists all normal files within a given directory. Recursive function. Can also return the list of directories in the second parameter by reference.
   276  * Lists all normal files within a given directory. Recursive function. Can also return the list of directories in the second parameter by reference.
   277  * @param string Directory to search
   277  * @param string Directory to search
   279  * @return array Not multi-depth
   279  * @return array Not multi-depth
   280  */
   280  */
   281 
   281 
   282 function gal_dir_recurse($dir, &$dirlist)
   282 function gal_dir_recurse($dir, &$dirlist)
   283 {
   283 {
   284   $dir_handle = opendir($dir);
   284 	$dir_handle = opendir($dir);
   285   if ( !$dir_handle )
   285 	if ( !$dir_handle )
   286     return false;
   286 		return false;
   287   $entries = array();
   287 	$entries = array();
   288   $dirlist = array();
   288 	$dirlist = array();
   289   while ( true )
   289 	while ( true )
   290   {
   290 	{
   291     $file = readdir($dir_handle);
   291 		$file = readdir($dir_handle);
   292     if ( !$file )
   292 		if ( !$file )
   293       break;
   293 			break;
   294     if ( $file == '.' || $file == '..' )
   294 		if ( $file == '.' || $file == '..' )
   295       continue;
   295 			continue;
   296     $file = $dir . '/' . $file;
   296 		$file = $dir . '/' . $file;
   297     if ( is_dir($file) )
   297 		if ( is_dir($file) )
   298     {
   298 		{
   299       $children = gal_dir_recurse($file, $dirtemp);
   299 			$children = gal_dir_recurse($file, $dirtemp);
   300       $dirlist[] = $file;
   300 			$dirlist[] = $file;
   301       $dirlist = array_merge($dirlist, $dirtemp);
   301 			$dirlist = array_merge($dirlist, $dirtemp);
   302       $entries = array_merge($entries, $children);
   302 			$entries = array_merge($entries, $children);
   303     }
   303 		}
   304     else if ( is_file($file) )
   304 		else if ( is_file($file) )
   305     {
   305 		{
   306       $entries[] = $file;
   306 			$entries[] = $file;
   307     }
   307 		}
   308     else
   308 		else
   309     {
   309 		{
   310       die($file . ' is not a file or directory');
   310 			die($file . ' is not a file or directory');
   311     }
   311 		}
   312   }
   312 	}
   313   closedir($dir_handle);
   313 	closedir($dir_handle);
   314   return $entries;
   314 	return $entries;
   315 }
   315 }
   316 
   316 
   317 /**
   317 /**
   318  * Wrapper for JSON decoding that works on Enano 1.0.x and 1.1.x
   318  * Wrapper for JSON decoding that works on Enano 1.0.x and 1.1.x
   319  * @param string JSON datastream...
   319  * @param string JSON datastream...
   320  * @return mixed
   320  * @return mixed
   321  */
   321  */
   322 
   322 
   323 function snapr_json_decode($data)
   323 function snapr_json_decode($data)
   324 {
   324 {
   325   if ( defined('ENANO_ATLEAST_1_1') )
   325 	if ( defined('ENANO_ATLEAST_1_1') )
   326   {
   326 	{
   327     try
   327 		try
   328     {
   328 		{
   329       $decoded = enano_json_decode($data);
   329 			$decoded = enano_json_decode($data);
   330     }
   330 		}
   331     catch ( Exception $e )
   331 		catch ( Exception $e )
   332     {
   332 		{
   333       $response = array(
   333 			$response = array(
   334         'mode' => 'error',
   334 				'mode' => 'error',
   335         'error' => 'Exception in JSON parser.'
   335 				'error' => 'Exception in JSON parser.'
   336       );
   336 			);
   337       die(enano_json_encode($response));
   337 			die(enano_json_encode($response));
   338     }
   338 		}
   339   }
   339 	}
   340   else
   340 	else
   341   {
   341 	{
   342     $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
   342 		$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
   343     $decoded = $json->decode($data);
   343 		$decoded = $json->decode($data);
   344   }
   344 	}
   345   return ( isset($decoded) ) ? $decoded : false;
   345 	return ( isset($decoded) ) ? $decoded : false;
   346 }
   346 }
   347 
   347 
   348 /**
   348 /**
   349  * Wrapper for JSON encoding that works on Enano 1.0.x and 1.1.x
   349  * Wrapper for JSON encoding that works on Enano 1.0.x and 1.1.x
   350  * @param mixed Data to encode
   350  * @param mixed Data to encode
   351  * @return string
   351  * @return string
   352  */
   352  */
   353 
   353 
   354 function snapr_json_encode($data)
   354 function snapr_json_encode($data)
   355 {
   355 {
   356   if ( defined('ENANO_ATLEAST_1_1') )
   356 	if ( defined('ENANO_ATLEAST_1_1') )
   357   {
   357 	{
   358     try
   358 		try
   359     {
   359 		{
   360       $encoded = enano_json_encode($data);
   360 			$encoded = enano_json_encode($data);
   361     }
   361 		}
   362     catch ( Exception $e )
   362 		catch ( Exception $e )
   363     {
   363 		{
   364       $response = array(
   364 			$response = array(
   365         'mode' => 'error',
   365 				'mode' => 'error',
   366         'error' => 'Exception in JSON encoder.'
   366 				'error' => 'Exception in JSON encoder.'
   367       );
   367 			);
   368       die(enano_json_encode($response));
   368 			die(enano_json_encode($response));
   369     }
   369 		}
   370   }
   370 	}
   371   else
   371 	else
   372   {
   372 	{
   373     $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
   373 		$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
   374     $encoded = $json->encode($data);
   374 		$encoded = $json->encode($data);
   375   }
   375 	}
   376   return ( isset($encoded) ) ? $encoded : false;
   376 	return ( isset($encoded) ) ? $encoded : false;
   377 }
   377 }
   378 
   378 
   379 ?>
   379 /**
       
   380  * Is the given file extension allowed?
       
   381  * @param string
       
   382  * @return bool
       
   383  */
       
   384 
       
   385 function snapr_extension_allowed($ext)
       
   386 {
       
   387 	$allowedext = array('png', 'jpg', 'jpeg', 'tiff', 'tif', 'bmp', 'gif');
       
   388 	return in_array(strtolower($ext), $allowedext);
       
   389 }
       
   390 
       
   391 /**
       
   392  * Process (make thumbnails for) an uploaded image.
       
   393  * @param int image_id
       
   394  * @return bool
       
   395  */
       
   396 
       
   397 function snapr_process_image($image_id)
       
   398 {
       
   399 	global $db, $session, $paths, $template, $plugins; // Common objects
       
   400 	
       
   401 	$q = $db->sql_query('SELECT img_filename FROM ' . table_prefix . "gallery WHERE img_id = $image_id AND processed = 0 AND is_folder = 0;");
       
   402 	if ( !$q )
       
   403 		$db->_die();
       
   404 	if ( $db->numrows() < 1 )
       
   405 	{
       
   406 		$db->free_result();
       
   407 		return false;
       
   408 	}
       
   409 	list($filename) = $db->fetchrow_num($q);
       
   410 	$db->free_result();
       
   411 	
       
   412 	$orig_path = ENANO_ROOT . "/files/$filename";
       
   413 	$thumb = ENANO_ROOT . "/cache/$filename-thumb.jpg";
       
   414 	$preview = ENANO_ROOT . "/cache/$filename-preview.jpg";
       
   415 	
       
   416 	// create thumbnail
       
   417 	if ( !scale_image($orig_path, $thumb, 80, 80, true) )
       
   418 		return false;
       
   419 	// create preview
       
   420 	if ( !scale_image($orig_path, $preview, 640, 1000, true) )
       
   421 		return false;
       
   422 	
       
   423 	$q = $db->sql_query('UPDATE ' . table_prefix . "gallery SET processed = 1 WHERE img_id = $image_id;");
       
   424 	if ( !$q )
       
   425 		$db->_die();
       
   426 	
       
   427 	return true;
       
   428 }
       
   429 
       
   430 /**
       
   431  * Simple function to add an image to the database. Needs only the file path and the folder to put it in.
       
   432  * @param string Filename
       
   433  * @param int Folder, defaults to NULL (root)
       
   434  * @return int image ID
       
   435  */
       
   436 
       
   437 function snapr_insert_image($path, $folder_id = NULL)
       
   438 {
       
   439 	global $db, $session, $paths, $template, $plugins; // Common objects
       
   440 	
       
   441 	$ext = get_file_extension($path);
       
   442 	$ourfilename = gallery_make_filename() . "." . strtolower($ext);
       
   443 	if ( !snapr_extension_allowed($ext) )
       
   444 		return false;
       
   445 	
       
   446 	// copy the file to the storage folder
       
   447 	if ( !rename($path, ENANO_ROOT . "/files/$ourfilename") )
       
   448 		return false;
       
   449 	
       
   450 	// insert the image into the database
       
   451 	$folder = $folder_id === NULL ? 'NULL' : strval(intval($folder_id));
       
   452 	$title = ucwords(str_replace('_', ' ', basename($path)));
       
   453 	$title = preg_replace("/\.{$ext}\$/i", '', $title);
       
   454 	$sz = serialize(array());
       
   455 	$now = time();
       
   456 	$q = $db->sql_query('INSERT INTO ' . table_prefix . "gallery(is_folder, folder_parent, img_title, print_sizes, img_filename, img_time_upload, img_time_mod, img_tags, img_author, processed) VALUES\n"
       
   457 		              . "	(0, $folder, '$title', '$sz', '$ourfilename', $now, $now, '[]', $session->user_id, 0);");
       
   458 	if ( !$q )
       
   459 		$db->_die();
       
   460 	
       
   461 	return $db->insert_id();
       
   462 }
       
   463 
       
   464 /**
       
   465  * Process an uploaded zip file.
       
   466  * @param string Zip file
       
   467  * @param int Folder ID, defaults to NULL (root)
       
   468  * @return array of image IDs
       
   469  */
       
   470 
       
   471 function snapr_process_zip($path, $folder_id = NULL)
       
   472 {
       
   473 	error_reporting(E_ALL);
       
   474 
       
   475 	if ( !mkdir(ENANO_ROOT . '/cache/temp') )
       
   476 		return false;
       
   477 	$temp_dir = tempnam(ENANO_ROOT . '/cache/temp', 'galunz');
       
   478 	if ( file_exists($temp_dir) )
       
   479 		unlink($temp_dir);
       
   480 	@mkdir($temp_dir);
       
   481 	
       
   482 	// Extract the zip file
       
   483 	if ( class_exists('ZipArchive') )
       
   484 	{
       
   485 		$zip = new ZipArchive();
       
   486 		$op = $zip->open($file['tmp_name']);
       
   487 		if ( !$op )
       
   488 		{
       
   489 			return false;
       
   490 		}
       
   491 		$op = $zip->extractTo($temp_dir);
       
   492 		if ( !$op )
       
   493 		{
       
   494 			return false;
       
   495 		}
       
   496 	}
       
   497 	else if ( file_exists('/usr/bin/unzip') )
       
   498 	{
       
   499 		$cmd = "/usr/bin/unzip -qq -d '$temp_dir' {$path}";
       
   500 		system($cmd);
       
   501 	}
       
   502 	
       
   503 	// Any files?
       
   504 	$file_list = gal_dir_recurse($temp_dir, $dirs);
       
   505 	if ( !$file_list )
       
   506 	{
       
   507 		return false;
       
   508 	}
       
   509 	if ( count($file_list) < 1 )
       
   510 	{
       
   511 		return false;
       
   512 	}
       
   513 	
       
   514 	$dirs = array_reverse($dirs);
       
   515 	$img_files = array();
       
   516 	
       
   517 	// Loop through and add files
       
   518 	foreach ( $file_list as $file )
       
   519 	{
       
   520 		$ext = get_file_extension($file);
       
   521 		
       
   522 		if ( snapr_extension_allowed($ext) )
       
   523 		{
       
   524 			$img_files[] = $file;
       
   525 		}
       
   526 		else
       
   527 		{
       
   528 			unlink($file);
       
   529 		}
       
   530 	}
       
   531 	
       
   532 	// Main storage loop
       
   533 	$results = array();
       
   534 	foreach ( $img_files as $file )
       
   535 	{
       
   536 		$result = snapr_insert_image($file, $folder_id);
       
   537 		if ( $result !== false )
       
   538 			$results[] = $result;
       
   539 	}
       
   540 	
       
   541 	// clean up
       
   542 	foreach ( $dirs as $dir )
       
   543 	{
       
   544 		rmdir($dir);
       
   545 	}
       
   546 	
       
   547 	if ( !rmdir( $temp_dir ) )
       
   548 		return false;
       
   549 	if ( !rmdir( ENANO_ROOT . '/cache/temp' ) )
       
   550 		return false;
       
   551 		
       
   552 	return $results;
       
   553 }