PicasaRandomImage::get_random_image()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
nop 1
1
<?php
0 ignored issues
show
Coding Style introduced by
File has mixed line endings; this may cause incorrect results
Loading history...
2
3
/**
4
 * adds pictures from your google picasa account to a data object for random retrieval.
5
 *@author nicolaas[at]sunnysideup.co.nz
6
 * example link: https://picasaweb.google.com/data/feed/api/user/xxx
7
 * example link: https://picasaweb.google.com/data/feed/api/user/nfrancken/albumid/5742357499437955281xxxx/
8
 * large image: https://lh4.googleusercontent.com/-zs8sog5SG0U/T7DzuF3Lw9I/AAAAAAAAP4E/rPZiGlVL_eY/s2500/IMG_1715.JPG
9
 * (Note 2500 as the width!)
10
 *
11
 *
12
 **/
13
14
class PicasaRandomImage extends DataObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
15
{
16
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
17
        "URL" => "Text",
18
        "DoNotUse" => "Boolean",
19
        "Selected" => "Boolean"
20
    );
21
22
23
    /**
24
     * google username e.g. firstname.lastname (if your email address is [email protected])
25
     * @var string
26
     */
27
    private static $google_username = '';
28
29
    /**
30
     * set to 30 to take one in thirty albums
31
     * set to 1 to take all
32
     * @var Int
33
     */
34
    private static $number_of_folders = 22;
0 ignored issues
show
Unused Code introduced by
The property $number_of_folders is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
35
36
    /**
37
     * set to 30 to take one in thirty pictures
38
     * set to 1 to add all
39
     * @var Int
40
     */
41
    private static $number_of_images_per_folder = 7;
0 ignored issues
show
Unused Code introduced by
The property $number_of_images_per_folder is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
42
43
    public static function get_random_image($width)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
44
    {
45
        $objects = PicasaRandomImage::get()->filter(
46
            array("DoNotUse" => 0)
47
        )
48
        ->sort("RAND()");
49
        if ($objects && $obj = $objects->First()) {
50
            $obj->URL = str_replace('/s72/', '/s'.$width.'/', $obj->URL);
51
            return $obj;
52
        }
53
    }
54
55
    public function requireDefaultRecords()
0 ignored issues
show
Coding Style introduced by
requireDefaultRecords uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
56
    {
57
        parent::requireDefaultRecords();
58
        if (isset($_GET["updatepicassapics"])) {
59
            $albums = $this->getAlbums(PicasaRandomImage::$google_username);
60
            if (is_array($albums) && count($albums)) {
61
                $selectedAlbums = array_rand($albums, (count($albums <= self::get_number_of_folders()) ? self::get_number_of_folders() : count($albums)));
0 ignored issues
show
Bug introduced by
The method get_number_of_folders() does not seem to exist on object<PicasaRandomImage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
62
                if (!is_array($selectedAlbums)) {
63
                    $selectedAlbums = array($selectedAlbums);
64
                }
65
                foreach ($selectedAlbums as $albumKey) {
66
                    $albumTitle = $albums[$albumKey];
67
                    //google wants only the letters and numbers in the url
68
                    $albumTitle = preg_replace("[^A-Za-z0-9]", "", $albumTitle);
69
                    //get the list of pictures from the album
70
                    $pictures = $this->showAlbumContent(PicasaRandomImage::$google_username, $albumTitle);
71
                    if (is_array($pictures) && count($pictures)) {
72
                        $selectedPictures = array_rand($pictures, (count($pictures <= self::get_number_of_images_per_folder()) ? self::get_number_of_images_per_folder() : count($pictures)));
0 ignored issues
show
Bug introduced by
The method get_number_of_images_per_folder() does not seem to exist on object<PicasaRandomImage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
                        //get a random picture from the album
74
                        if (!is_array($selectedPictures)) {
75
                            $selectedPictures = array($selectedPictures);
76
                        }
77
                        foreach ($selectedPictures as $pictureKey) {
78
                            $picture = $pictures[$pictureKey];
79
                            $url = $picture["src"];
80
                            if ($obj = PicasaRandomImage::get()->filter(array("URL" => $url))->first()) {
0 ignored issues
show
Unused Code introduced by
$obj is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
81
                                //do nothing
82
                            } else {
83
                                $obj = new PicasaRandomImage();
84
                                $obj->URL = $url;
0 ignored issues
show
Documentation introduced by
The property URL does not exist on object<PicasaRandomImage>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
85
                                $obj->write();
86
                                DB::alteration_message("adding picasa random image: ".$obj->URL."<img src=\"$url\" alt=\"\">", "created");
0 ignored issues
show
Documentation introduced by
The property URL does not exist on object<PicasaRandomImage>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
87
                            }
88
                        }
89
                    }
90
                }
91
            }
92
        }
93
    }
94
95
    //GET THE REMOTE FILE INTO A VARIABLE
96
    protected function curlit($url)
97
    {
98
        $ch = curl_init();
99
        curl_setopt($ch, CURLOPT_URL, $url);
100
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
101
        $return=curl_exec($ch);
102
        curl_close($ch);
103
        return $return;
104
    }
105
106
    //THIS IS BASED ON http://blogoscoped.com/archive/2007-03-22-n84.html
107
    protected function getAlbums($userId)
108
    {
109
        $tmp = array();
110
111
        $url = 'http://picasaweb.google.com/data/feed/api/user/' . urlencode($userId) . '?kind=album';
112
        $xml = $this->curlit($url);
113
        $xml = str_replace("xmlns='http://www.w3.org/2005/Atom'", '', $xml);
114
        $dom = new domdocument;
115
        if ($xml) {
116
            $dom->loadXml($xml);
117
118
            $xpath = new domxpath($dom);
119
            $nodes = $xpath->query('//entry');
120
121
            foreach ($nodes as $node) {
122
                $rights = $xpath->query('rights', $node)->item(0)->textContent;
123
                if ($rights == "public") {
124
                    $tmp[] = $xpath->query('title', $node)->item(0)->textContent;
125
                }
126
            }
127
        }
128
        return $tmp;
129
    }
130
131
    //THIS IS BASED ON http://blogoscoped.com/archive/2007-03-22-n84.html
132
    protected function showAlbumContent($userId, $albumName)
133
    {
134
        $tmp = array();
135
        $url = 'http://picasaweb.google.com/data/feed/api/user/' . urlencode($userId) . '/album/'.$albumName."/";
136
        $xml = $this->curlit($url);
137
        $xml = str_replace("xmlns='http://www.w3.org/2005/Atom'", '', $xml);
138
        if ($xml == "No album found.") {
139
            DB::alteration_message("$albumName NOT FOUND", "deleted");
140
            return $tmp;
141
        }
142
        $dom = new domdocument;
143
        if ($xml) {
144
            $dom->loadXml($xml);
145
            $xpath = new domxpath($dom);
146
            $nodes = $xpath->query('//entry');
147
            foreach ($nodes as $node) {
148
                $tmp[]['src'] = $xpath->query('.//media:thumbnail/@url', $node)->item(0)->textContent;
149
            }
150
        }
151
        return $tmp;
152
    }
153
}
154
155
156
class PicasaRandomImage_Controller extends ContentController
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
157
{
158
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $allowed_actions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
159
        "one" => "ADMIN",
160
        "review" => "ADMIN",
161
        "donotuse" => "ADMIN",
162
        "select" => "ADMIN",
163
        "mylist" => "ADMIN"
164
    );
165
166
    public function one($request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
167
    {
168
        $width = $request->Param("ID");
169
        $image = PicasaRandomImage::get_random_image($width);
170
        if ($image) {
171
            return $image->URL;
172
        }
173
    }
174
175
    public function review($request)
176
    {
177
        echo "<html><head></head><body></body>
178
		<h2>Review Pictures</h2>
179
		<p>Click on pixies that you do not want to use.</p>
180
		<ul>";
181
        $width = $request->Param("ID");
182
        if (!$limit) {
0 ignored issues
show
Bug introduced by
The variable $limit seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
183
            $width = 400;
184
        }
185
        $limit = $request->Param("OtherID");
186
        if (!$limit) {
187
            $limit = 0;
188
        }
189
        $objects = PicasaRandomImage::get()->sort("ID", "ASC")->limit(100, $limit);
190
        if ($objects->count()) {
191
            foreach ($objects as $obj) {
192
                $obj->URL = str_replace('/s72/', '/s'.$width.'/', $obj->URL);
193
                $style = "";
194
                if ($obj->Selected) {
195
                    $style = "style=\"background-color: green;\"";
196
                }
197
                if ($obj->DoNotUse) {
198
                    $style = "style=\"opacity: 0.3\"";
199
                }
200
                echo "
201
				<li $style>
202
					<a href=\"/randompicassaimage/donotuse/".$obj->ID."/\" class=\"remove\" style=\"float: right;\">remove</a>
203
					<a href=\"/randompicassaimage/select/".$obj->ID."/\" class=\"select\">select</a>
204
					<img src=\"".$obj->URL."\" alt=\"\" />
205
					<hr style=\"clear: both\" />
206
				</li>";
207
            }
208
        }
209
        $limit = $limit + 100;
210
        echo "
211
		</ul><a href=\"/randompicassaimage/review/400/$limit/\">next 100</a>";
212
        echo "
213
		<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"></script>
214
		<script type=\"text/javascript\">
215
			jQuery(\"a.remove\").click(
216
				function(event){
217
					event.preventDefault();
218
					var url = jQuery(this).attr(\"href\");
219
					var holder = jQuery(this).parents(\"li\");
220
					jQuery.get(
221
						url,
222
						function() {
223
							holder.fadeOut();
224
						}
225
					);
226
				}
227
			);
228
			jQuery(\"a.select\").click(
229
				function(event){
230
					event.preventDefault();
231
					var url = jQuery(this).attr(\"href\");
232
					var holder = jQuery(this).parents(\"li\");
233
					jQuery.get(
234
						url,
235
						function() {
236
							holder.css(\"backgroundColor\", \"green\");
237
						}
238
					);
239
				}
240
			);
241
		</script>
242
		</body></html>";
243
    }
244
245
246
    public function mylist($request)
247
    {
248
        echo "\$array = array(";
249
        $width = $request->Param("ID");
250
        if (!$width) {
251
            $width = 2400;
252
        }
253
        $objects = PicasaRandomImage::get()->filter(array("DoNotUse" => 0, "Selected" => 1));
254
        if ($objects->count()) {
255
            foreach ($objects as $obj) {
256
                if ($obj->URL) {
257
                    $obj->URL = str_replace('/s72/', '/s'.$width.'/', $obj->URL);
258
                    echo "\r\n";
259
                    echo "\t'".$obj->URL."'";
260
                    if (!$obj->Last()) {
261
                        echo ",";
262
                    }
263
                }
264
            }
265
        }
266
        echo "\r\n);";
267
    }
268
269 View Code Duplication
    public function donotuse($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
    {
271
        $id = intval($request->Param("ID"));
272
        if ($obj = PicasaRandomImage::get()->byID($id)) {
273
            $obj->DoNotUse = 1;
274
            $obj->write();
275
            return "deleted";
276
        }
277
    }
278
279 View Code Duplication
    public function select($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
280
    {
281
        $id = intval($request->Param("ID"));
282
        if ($obj = PicasaRandomImage::get()->byID($id)) {
283
            $obj->DoNotUse = 0;
284
            $obj->Selected = 1;
285
            $obj->write();
286
            return "selected";
287
        }
288
    }
289
}
290